Google Chrome Tabs Execute Script - javascript

I'm trying to develop a google chrome extension that scrape out specific data from the page once the page is finished loading. I'm trying to achieve it by executing a javascript file by setting file : 'js/scrape.js' and runAt: 'document_idle'.
However, setting selected : false does work but selected : true doesn't.
index.js:
var crawler = function() {
return {
init : function() {
document.getElementById('open').addEventListener('click', this.open);
},
open : function() {
var url = document.getElementById('url').value;
chrome.tabs.create({
url : url,
selected : true //doesn't work, setting to false does work
}, function(tab) {
chrome.tabs.executeScript(tab.id, {
file : 'js/scrape.js',
runAt : 'document_idle'
});
});
}
}}()
document.addEventListener('DOMContentLoaded', function() {
crawler.init();
});
I included index.js inside popup.html:
<script type="text/javascript" src="index.js"></script>
Finally, manifest.json:
{
"manifest_version": 2,
"name": "Crawler",
"description": "Scrape out the crap.",
"version": "1.0",
"permissions": ["tabs", "http://*/*", "https://*/*"],
"browser_action": {
"default_title": "Scrape out the crap",
"default_icon": "icon.png",
"default_popup": "popup.html"
}
}

Using active => true fixed the issue. I missed the part of the documentation that explains it.

Related

Running chrome extension process while popup is closed

Basically I am trying to create an Auto Visitor Extension for Chrome to open a website's URL after some specific time. When I open the popup everything works fine but when the popup is close nothing works. I am trying to find out a method to run that Auto Visitor Extension even when the popup is close I have read multiple questions regarding this phenomena on Stack Overflow but none of them clarifies what I am looking for.
Here is my manifest file:
manifest.json
{
"manifest_version": 2,
"name": "Auto Visitor",
"description": "This extension will visit multiple pages you saved in extension",
"version": "1.0",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"background": {
"scripts": [
"background.js"
],
"persistent": false
},
"permissions": [
"activeTab",
"storage",
"tabs",
"http://*/",
"https://*/"
]
}
The background file that i want to run even when popup is close :
background.js
// this will work only when you denie the background script in manifest
chrome.runtime.onInstalled.addListener(function(details) {
var initTime = 5;
chrome.storage.local.set({"avtime": initTime}, function() {});
});
reloadMainTab();
function reloadMainTab() {
chrome.storage.local.get('avurl', function (result) {
var urlsToLoad = result.avurl;
console.log(urlsToLoad);
if(urlsToLoad==undefined){
// do nothing
}else{
var urlsArr = urlsToLoad.split(",");
chrome.storage.local.get('avtime', function (result) {
var thisTime = result.avtime;
/*
setting it to -1 because it gets incremented by 1
when it goes into getSelected method
*/
var index=-1;
setInterval(function(){
if(index < urlsArr.length-1){
chrome.tabs.getSelected(function (tab) {
// console.log('index in get selected'+index)
chrome.tabs.update(tab.id,{url: urlsArr[index]});
});
index++;
}else{
index=-1;
}
}, thisTime+"000");
});
}
});
}
any help would be really appreciated

Content Script fails to run when navigating to a new link

I am currently writing a Google chrome extension that needs to run on YouTube videos. I have a content script which is a JavaScript file that does all the work I need it to do.
It is working fine, the only caveat is that for some reason, whenever you click a link to go to a new video, it doesn't run the JavaScript code immediately; you need to reload the page to make it work.
manifest.json
{
"name": "Title",
"description": "description",
"version": "0.5",
"permissions": [
"webNavigation",
"activeTab",
"tabs",
"*://*.youtube.com/*"
],
"browser_action": {
"default_icon": {
"16": "image.png"
},
"default_title": "name",
"default_popup": "popup.html"
},
"content_scripts": [
{
"matches": ["*://*.youtube.com/*"],
"js": ["blocker.js"],
"run_at": "document_end"
}
],
"manifest_version": 2
}
blocker.js
myfunction();
function myfunction(){
//manipulate the HTML DOM
}
myfunction();
function myfunction(){
//manipulate the HTML DOM
}
You can put a time interval to detect that the URL changes
var currentURL = location.href;
setInterval(function() {
if(location.href != currentURL) {
myfunction();
currentURL = location.href
}
}, 100);
but I use this
var currentURL = location.href;
window.onclick=function(){
if(currentURL!==location.href){
myfunction();
currentURL = location.href
/*some code*/
}
}
HTML5 introduces a hashchange event which allows you to register for notifications of url hash changes without polling for them with a timer.
window.onhashchange = function (event) {
console.log(location.hash, event.oldURL, event.newURL);
myfunction();
}

Getting DOM in Chrome extension popup?

I'm trying to create a Chrome extension that displays the current page's DOM in a popup.
As a warmup, I tried putting a string in getBackgroundPage().dummy, and this is visible to the popup.js script. But, when I try saving the DOM in getBackgroundPage().domContent, popup.js just sees this as undefined.
Any idea what might be going wrong here?
I looked at this related post, but I couldn't quite figure out how to use the lessons from that post for my code.
Code:
background.js
chrome.extension.getBackgroundPage().dummy = "yo dummy";
function doStuffWithDOM(domContent) {
//console.log("I received the following DOM content:\n" + domContent);
alert("I received the following DOM content:\n" + domContent);
//theDomContent = domContent;
chrome.extension.getBackgroundPage().domContent = domContent;
}
chrome.tabs.onUpdated.addListener(function (tab) {
//communicate with content.js, get the DOM back...
chrome.tabs.sendMessage(tab.id, { text: "report_back" }, doStuffWithDOM); //FIXME (doesnt seem to get into doStuffWithDOM)
});
content.js
/* Listen for messages */
chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) {
/* If the received message has the expected format... */
if (msg.text && (msg.text == "report_back")) {
/* Call the specified callback, passing
the web-pages DOM content as argument */
//alert("hi from content script"); //DOESN'T WORK ... do we ever get in here?
sendResponse(document.all[0].outerHTML);
}
});
popup.js
document.write(chrome.extension.getBackgroundPage().dummy); //WORKS.
document.write(chrome.extension.getBackgroundPage().domContent); //FIXME (shows "undefined")
popup.html
<!doctype html>
<html>
<head>
<title>My popup that should display the DOM</title>
<script src="popup.js"></script>
</head>
</html>
manifest.json
{
"manifest_version": 2,
"name": "Get HTML example w/ popup",
"version": "0.0",
"background": {
"persistent": false,
"scripts": ["background.js"]
},
"content_scripts": [{
"matches": ["<all_urls>"],
"js": ["content.js"]
}],
"browser_action": {
"default_title": "Get HTML example",
"default_popup": "popup.html"
},
"permissions": ["tabs"]
}
You got the syntax of chrome.tabs.onUpdated wrong.
In background.js
chrome.tabs.onUpdated.addListener(function(id,changeInfo,tab){
if(changeInfo.status=='complete'){ //To send message after the webpage has loaded
chrome.tabs.sendMessage(tab.id, { text: "report_back" },function(response){
doStuffWithDOM(response);
});
}
})

chrome extension - login in popup.html using django backend

I am trying to accomplish this login process.
In the extension, there is popup.html, popup.js, background.js and content.js as usual.
In popup.html, there are username and password inputfields and login button.
My vision is: I will catch both inputs in popup.js and send them to background.js and from there, i will send them to django backend. django backend returns logged-in token.
firstly, is this possible way?
my first step is not working: i cannot send message from popup.js to background.js. no error in console, also no success. this is my code:
popup.js
handleLoginClick_: function(){
var email = this.email.value;
var pwd = this.pwd.value;
chrome.tabs.sendMessage(tab.id, {asking: "login"}, function(response) {
sendToDjango(response.answer);
});
}
background.js
chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
if (request.asking === "login"){
console.log('got msg from popup.js');
return;
}
});
what am I doing wrong?
this is the manifest.json:
{
"name" : "myBIZMark",
"version" : "1.1",
"description" : "collect competing company's keywords",
"permissions": [
"tabs", "contextMenus", "<all_urls>", "storage"
],
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"background": {
"persistent": false,
"scripts": ["jquery111.js","background.js"]
},
"manifest_version": 2,
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["jquery111.js", "contentscript.js","popup.js"]
}
]
}
Your message in popup.js is targeted toward the content scripts, not the background page. You need to use chrome.runtime, not chrome.tabs.
Replace:
chrome.tabs.sendMessage(tab.id, {asking: "login"}, function(response) {
sendToDjango(response.answer);
});
With:
chrome.runtime.sendMessage({asking: "login"}, function(response) {
sendToDjango(response.answer);
});
In summary:
chrome.tabs.sendMessage = background -> content
chrome.runtime.sendMessage = content -> background

console.log doesn't work from chrome.tabs.executeScript

I need to execute script once user clicked my context menu item.
So for the purpose I created the context menu from my background js:
chrome.contextMenus.create({"title": title, "contexts": contexts,
"onclick": genericOnClick});
It appears as expected. Later on from the genericOnClick I try to execute my script:
chrome.tabs.executeScript(null, {code: "console.log('test 1');"}, function() {
console.log("test 2");
});
I can see that the "test 2" is printed to console but "test 1" never gets printed. What am I doing wrong?
I've tried adding the console.log sentence to a separate js file but it failed to print it as well:
chrome.tabs.executeScript(null, {"file": 'content_script.js'}, function() {
console.log("test 2");
});
Note: my content_script.js is not defined in manifest. My manifest looks like follows:
{
"name": "My First Extension",
"version": "1.0",
"manifest_version": 2,
"description": "Sample extension",
"page_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": [
"http://*/*",
"https://*/*",
"tabs",
"contextMenus"
],
"background": {
"scripts": ["sample.js"]
},
"icons": {
"16": "icon16.png"
}
}
Thank you in advance.
The only piece of code from your extension that has access to the console is the content script that is injected into the original page.
From your code it looks like you are trying to write to the console from a background script. So, to write to the console from a background page you've to inject a content script to do the job for you.
In my extensions I use my own function to write messages to the console from a background script. The code for the same is given below:
function logMessage(msg){
chrome.tabs.executeScript({code:"console.log('"+msg+"')"});
}
Define the above as the first function in your background script and call it from anywhere in the background script to write messages to the console.
In your case you can use this from the genericOnClick function to write messages to the console.
// addListener
chrome.browserAction.onClicked.addListener(function() {
chrome.tabs.executeScript(null, {file: "content_script.js"}, function() {
console.log("test 2");
});
});
// Context Menu
chrome.contextMenus.create({
title: myTitle,
contexts: ['page'],
onclick: function (detail, tab) { fn(tab) }
});
so;
"permissions": [
"tabs", "http://*/*", "https://*/*"
]
chrome.tabs.executeScript(null,{code:"document.body.style.backgroundColor='red'"});
or:
// Functional structure
function hi() { alert("hi"); };
// hi function toString after run function (hi)()
chrome.tabs.executeScript(null, { code: "(" + hi.toString() + ")()" });

Categories

Resources