get all links in chrome extension - javascript

I'm trying to make an extension that collecting social networks links from the web page where user is. So when user clicking button getLinks we get all links and then by checking condition passing them in the blocks of the extension. I tried to use chrome.tabs.executeScript, and get links through urls = $$('a'); but it's not working
$('#getLinks').click(function(e)
{
var allLinks = [];
var i = 0;
chrome.tabs.executeScript( null, {"code": "urls = $$('a'); for (url in urls)
{ allLinks[i]=urls[url].href; i++;}"}, function() {
var vk;
var facebook;
var linkedin;
for (var i=0; i<allLinks.length; i++)
{
var profil = (allLinks[i].href);
if(profil.indexOf('vk.com')!=-1)
{
vk = profil;
$('#vk').text(vk);
}
if(profilito.indexOf('facebook.com')!=-1)
{
facebook = profil;
$('#fb').text(facebook);
}
if(profilito.indexOf('linkedin.com')!=-1)
{
linkedin = profil;
$('#linkin').text(linkedin);
}
}
});
});

That's not how executeScript is used. That code can not access the variables allLinks and i because it is executed elsewhere. But you can make use of the returned value of that code like in this other SO question:
$('#getLinks').click(function(e) {
chrome.tabs.executeScript( null, {"code": "var urls = document.querySelectorAll('a'); for(var i = 0; i < urls.length; i++) { urls[i] = urls[i].href; }; urls"}, function(results) {
var allLinks = results[0];
// use allLinks here
});
});

So finally I got an answer on my own question and posting here the solution
$('#getUser').click(function(e) {
chrome.tabs.executeScript(null,{code: 'Array.from(document.getElementsByTagName("a")).map(a => a.innerHTML)'},function (results){
var vk = [];
var facebook = [];
var linkedin = [];
var allElements = results[0];
for (var i=0; i<allElements.length; i++)
{
if (allElements[i].indexOf("https://vk.com") !== -1)
{
vk.push (allElements[i]);
}
if (allElements[i].indexOf("https://facebook.com") !== -1 )
{
facebook.push (allElements[i]);
}
if (allElements[i].indexOf("https://www.linkedin.com") !== -1 )
{
linkedin.push (allElements[i]);
}
}
});
All links that we are finding on the page sorted in 3 arrays by belonging to the social networks

Related

Update orders status Google Spreadsheet by checking the status in other Sheet using Google Apps Scripts

I'm working to get the status for orders to be updated in the master sheet. I have disconnected orders with status in another sheet named "Decommission sheet". While I update the master I need to check the status for these orders by applying the below logic:
If the order is DECOMMISSIONED && not available in decommission sheet
then the order is LIVE.
If the order is available in the decommission sheet then check the
status if it is DECOMMISSIONED then the order is DECOMMISSIONED.
I have done it in a totally different way but it doesn't work with me. Any help would be appreciated.
function pathstatus() {
var MasterSs = SpreadsheetApp.openById('ID');
var MsterSh = MasterSs.getSheetByName('Master Sheet');
var MasterData = MsterSh.getDataRange().getValues();
var DecommisstionSh = MasterSs.getSheetByName('Decommisstion');
var DecommisstionData=DecommisstionSh.getDataRange().getValues();
for(var x=0;x<MasterData.length;x++){
var MasterPathName =MasterData[x][2]
var Masterstatus=MasterData[x][6]
var MasterStage=MasterData[x][7]
if(MasterStage == "DECOMMISSIONED"){
for(var i=0;i<DecommisstionData.length;i++){
var DecommisstionPathName = DecommisstionData[i][2]
var DecommisstionStatus = DecommisstionData[i][7]
var DecommissionedDate = DecommisstionData[i][10]
if(DecommisstionPathName == MasterPathName && DecommisstionStatus == "COMPLETED") {
MasterData[x][6]="DECOMMISSIONED"
MasterData[x][12]=DecommissionedDate
}else {
MasterData[x][6]="LIVE"
}
}
}
}
MsterSh.getRange(2,1,MsterSh.getLastRow(),MsterSh.getLastColumn()).clearContent();
MsterSh.getRange(2,1,MasterData.length,MasterData[0].length).setValues(MasterData)
SpreadsheetApp.flush()
}
In another way
function myFunction() {
var MasterSs = SpreadsheetApp.openById('ID');
var MsterSh = MasterSs.getSheetByName('Master Sheet');
var MasterData = MsterSh.getDataRange().getValues();
var DecommisstionSh = MasterSs.getSheetByName('Decommisstion');
var DecommisstionData=DecommisstionSh.getDataRange().getValues();
MasterData.splice(0,1);
DecommisstionData.splice(0,1);
var Decommisstionpath = [];
var Decommisstionstatus = [];
for(var i=0;i<DecommisstionData.length;i++) {
Decommisstionpath.push(Number(DecommisstionData[i][2]))
Decommisstionstatus.push(DecommisstionData[i][7])
}
var i=0;
for(var x=0;x<MasterData.length && MasterData[x][3] != undefined ;x++) {
var OrderStage = MasterData[x][8]
if(OrderStage=='DECOMMISSIONED') {
var PathName = MasterData[x][2]
var index = Decommisstionpath.indexOf(PathName);
if(index == -1)
{MasterData[x][6]="LIVE" }
else{
MasterData[x][6]="Check"
}
}
}
MsterSh.getRange(2,1,MsterSh.getLastRow(),MsterSh.getLastColumn()).clearContent();
MsterSh.getRange(2,1,MasterData.length,MasterData[0].length).setValues(MasterData)
SpreadsheetApp.flush();
}
Neither function works properly

NightmareJS Nested Commands

I can't figure out how to do nested commands for Nightmare. Consider the following code:
let userLinks = await nightmare.evaluate(function(users, nightmare) {
for(var i = 0; i < users.length; i++) {
var matchResult = users[i].match(/.com\/(.*?)\?fref/);
if (matchResult) {
var newLink = document.createElement('a');
document.body.appendChild(newLink);
newLink.setAttribute('href', 'https://www.example.com/'+matchResult[1]);
nightmare.click('a[href="https://www.example.com/'+matchResult[1]+'"]'); // this won't work
}
}
return null;
}, users);
The nightmare.click() won't work. I get nightmare.click is not a function. How can this be done?

'Juggling Async' - Why does my solution not return anything at all?

After asking a question and getting a very helpful answer on what the 'Async Juggling' assignment in learnyounode was asking me to do, I set out to implement it myself.
The problem is, my setup isn't having any success! Even though I've referred to other solutions out there, my setup simply isn't returning any results when I do a learnyounode verify myscript.js.
GIST: jugglingAsync.js
var http = require('http');
var app = (function () {
// Private variables...
var responsesRemaining,
urls = [],
responses = [];
var displayResponses = function() {
for(var iterator in responses) {
console.log(responses[iterator]);
}
};
// Public scope...
var pub = {};
pub.main = function (args) {
responsesRemaining = args.length - 2;
// For every argument, push a URL and prep a response.
for(var i = 2; i < args.length; i++) {
urls.push(args[i]);
responses.push('');
}
// For every URL, set off an async request.
for(var iterator in urls) {
var i = iterator;
var url = urls[i];
http.get(url, function(response) {
response.setEncoding('utf8');
response.on('data', function(data) {
if(response.headers.host == url)
responses[i] += data;
});
response.on('end', function() {
if(--responsesRemaining == 0)
displayResponses();
});
});
}
};
return pub;
})();
app.main(process.argv);
Question: What am I doing wrong?
This line
for(var iterator in urls) {
doesn't do what you think it does. It actually loops over the properties of urls (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in). Instead, you have to do something like
for(var i = 0; i < urls.length; i++) {
var url = urls[i];
...
}
or
urls.forEach(function(url, index) {
...
});
In addition to not properly looping through the arrays inside the app module, I was also not properly concatenating data returned from the response.on('data') event. Originally I was doing...
responses[index] += data;
Instead, the correct thing to do was:
responses[index] = responses[index] + data;
Changing that, as well as the things noted by #arghbleargh got the 'Async Juggling' to fully verify!
I have tested my code and it all worked:
~ $ node juggling_async.js site1 site2 site3 site4 ...
The JS code does not limit only to three sites.
var http = require('http');
// Process all the site-names from the arguments and store them in sites[].
// This way does not limit the count to only 3 sites.
var sites = [];
(function loadSites() {
for(var i = 2, len = process.argv.length; i < len; ++i) {
var site = process.argv[i];
if(site.substr(0, 6) != 'http://') site = 'http://' + site;
sites.push(site);
}
})();
var home_pages = [];
var count = 0;
function httpGet(index) {
var home_page = '';
var site = sites[index];
http.get(site, function(res) {
res.setEncoding('utf8');
res.on('data', function(data) {
home_page += data;
});
res.on('end', function() {
++count;
home_pages[index] = home_page;
if(count == sites.length) {
// Yahoo! We have reached the last one.
for(var i = 0; i < sites.length; ++i) {
console.log('\n############ Site #' + (+i+1) + ': ' + sites[i]);
console.log(home_pages[i]);
console.log('============================================\n');
}
}
});
})
.on('error', function(e) {
console.log('Error at loop index ' + inddex + ': ' + e.message);
})
;
}
for(var i = 0; i < sites.length; ++i) {
httpGet(i);
}

capture network resource requests on casper.click()

with casper.on("resource.requested"), we can capture the resource requests and perform checks for evaluation.
On page load, we are pushing all the network requests URL in an array and then traverse the array to find the number of calls to GOOGLE Analytics (i.e. _utm.gif).
// google analytics calls testing
casper.test.begin('Test Container Tags', function suite(test) {
casper.start("http://www.viget.com/", function() {
});
var urls = [],
links = [];
casper.on('resource.requested', function(requestData, resource) {
urls.push(decodeURI(requestData.url));
});
casper.then(function() {
var index = -1;
var found = 0;
for (var i = 0; i < urls.length; i++)
{
index = urls[i].indexOf('__utm.gif');
if (index > -1)
found = found+1;
}
casper.echo('found' + found);
test.assert(found > 0, 'Page Load Test Complete');
});
//Emit "resource.requested" to capture the network request on link click
casper.then(function(self) {
var utils = require('utils');
var x = require('casper').selectXPath;
casper.click(x("//a[data-type]"));
casper.emit('resource.requested');
});
casper.run(function() {
test.done();
});
});
But, now the next Ask is to verify the network resource requests on hyperlinks click event. Tried to make that work with casper.emit("resource.requested") but no success.
Already spent one complete day to find the workaround for the same. ANY feedback would be appreciated at this point.
You could use a casper.waitForResource() after the click and do your validation there.
casper.test.begin('Test Container Tags', function suite(test) {
casper.start("http://www.viget.com/", function() {
});
var urls = [],
links = [];
casper.on('resource.requested', function(requestData, resource) {
urls.push(decodeURI(requestData.url));
});
casper.then(function() {
var index = -1;
var found = 0;
for (var i = 0; i < urls.length; i++)
{
index = urls[i].indexOf('__utm.gif');
if (index > -1)
found = found+1;
}
casper.echo('found' + found);
test.assert(found > 0, 'Page Load Test Complete');
});
//Emit "resource.requested" to capture the network request on link click
casper.then(function(self) {
var utils = require('utils');
var x = require('casper').selectXPath;
casper.click(x("//a[data-type]"));
});
casper.waitForResource(function testResource(resource) {
console.log('----->' + resource.url);
});
casper.run(function() {
test.done();
});
});

How do get param from a url

As seen below I'm trying to get #currentpage to pass client params
Can someone help out thanks.
$(document).ready(function() {
window.addEventListener("load", windowLoaded, false);
function windowLoaded() {
chrome.tabs.getSelected(null, function(tab) {
document.getElementById('currentpage').innerHTML = tab.url;
});
}
var url = $("currentpage");
// yes I relize this is the part not working.
var client = jQuery.param("currentpage");
var page = jQuery.param("currentpage");
var devurl = "http://#/?clientsNumber=" + client + "&pageName=" + page ;
});
This is a method to extract the params from a url
function getUrlParams(url) {
var paramMap = {};
var questionMark = url.indexOf('?');
if (questionMark == -1) {
return paramMap;
}
var parts = url.substring(questionMark + 1).split("&");
for (var i = 0; i < parts.length; i ++) {
var component = parts[i].split("=");
paramMap [decodeURIComponent(component[0])] = decodeURIComponent(component[1]);
}
return paramMap;
}
Here's how to use it in your code
var url = "?c=231171&p=home";
var params = getUrlParams(url);
var devurl = "http://site.com/?c=" + encodeURIComponent(params.c) + "&p=" + encodeURIComponent(params.p) + "&genphase2=true";
// devurl == "http://site.com/?c=231171&p=home&genphase2=true"
See it in action http://jsfiddle.net/mendesjuan/TCpsD/
Here's the code you posted with minimal changes to get it working, it also uses $.param as it's intended, that is to create a query string from a JS object, this works well since my suggested function returns an object from the url
$(document).ready(function() {
// This does not handle arrays because it's not part of the official specs
// PHP and some other server side languages support it but there's no official
// consensus
function getUrlParams(url) {
var paramMap = {};
var questionMark = url.indexOf('?');
if (questionMark == -1) {
return paramMap;
}
var parts = url.substring(questionMark + 1).split("&");
for (var i = 0; i < parts.length; i ++) {
var component = parts[i].split("=");
paramMap [decodeURIComponent(component[0])] = decodeURIComponent(component[1]);
}
return paramMap;
}
// no need for the extra load listener here, jquery.ready already puts
// your code in the onload
chrome.tabs.getSelected(null, function(tab) {
document.getElementById('currentpage').innerHTML = tab.url;
});
var url = $("currentpage");
var paramMap = getUrlParams(url);
// Add the genphase parameter to the param map
paramMap.genphase2 = true;
// Use jQuery.param to create the url to click on
var devurl = "http://site.com/?"+ jQuery.param(paramMap);
$('#mydev').click( function(){
window.open(devurl);
});
});

Categories

Resources