How to stop content script from starting itself - javascript

My manifest.json matches every URL. So, whenever, a URL is opened in Chrome, the content script is activated.
Current procedure:
(1) My background script updates the current empty URL to something.
(2) My content script is activated, because it's a match in the manifest.json. My content script needs to visit multiple URLs on the same website. It clicks on a link and navigates back (= everything in one tab) -> The content script calls itself again, because another URL is opened.
Problem:
I don't want content script to call itself multiple times. It should for example only activate, when it gets a message from the background script that a new URL was opened.
Thoughts:
chrome.windows.onCreated.addListener(function()) is around all my code in the background script. Is there something similar for the content script that i'm looking for?
Maybe something like:
window.addEventListener
browser.runtime.onMessage.addListener
browser.runtime.sendMessage
browser.runtime.onMessage
browser.tabs.sendMessage()
But i don't understand how to use them properly.

In your background script, do this:
chrome.windows.onCreated.addListener(function(tab) {
let msg = {txt: "execute"};
chrome.tabs.sendMessage(tab.id, msg);
};
And then in your content script, you can intercept this message via:
chrome.runtime.onMessage.addListener(function(msg){
if(msg.txt == "execute") {
doSomething();
}
});
Docs here.
https://developer.chrome.com/extensions/runtime#method-sendMessage
https://developer.chrome.com/extensions/runtime#event-onMessage

Related

In background script, listen for newly opened tab

In my background script, or anywhere but a content script, I am trying to listen for the active tab, or a newly opened tab.
I have this, but this is apparently incorrect:
What I am trying to do is to inject a content-script into the active tab. I don't want my content script to run for every tab/window, just for select tabs.
Does anyone know how to inject a content script for certain tabs? I can't figure it out. I assume the best way to inject content scripts is from the background script.
If you want to run a code in already activated tab (chrome.tabs.query):
chrome.tabs.query({active: true, currentWindow: true}, function(foundTabs) {
const activeTabId = foundTabs[0].id;
chrome.tabs.executeScript(activeTabId, {
file: 'inject.js'
});
})
In case you want to inject a file into every newly activated tab (chrome.tabs.onActivated):
chrome.tabs.onActivated.addListener(function(activeInfo) {
chrome.tabs.executeScript(activeInfo.tabId, {
file: 'inject.js'
});
});
Be sure to check if you have injected the file already, in order to prevent multiple injections.
For both cases, permissions should include tabs.
I was missing the:
"webNavigation"
permission in manifest.json. After adding that permission, I now have:
chrome.webNavigation.onDOMContentLoaded.addListener(function (details) {
const tabId = details.tabId;
chrome.tabs.executeScript(tabId, {
file: 'inject.js'
});
});
now it works.
some chrome API we cant access in content script in that case do that code in background.js and do according action from background js. if you want to do some action in content script in that case you need to communicate using send message

bookmarklet that works on 2 pages

I'm using a bookmarklet to inject javascript into a webpage. I am trying to login into my gmail account(that part works) and in my gmail account automatically click Sent folder as the page loads. This is the starting page:
This is the code I am using in bookmarklet:
javascript:
document.getElementById('Email').value='myEmail#gmail.com';
document.getElementById('next').click();
setTimeout(function(){
document.getElementById('Passwd').value='myPassword';
document.getElementById('signIn').click();},1000);
setTimeout(function(){
document.getElementsByClassName("J-Ke n0 aBU")[0].click();
},6000);
J-Ke n0 aBU is the class of Sent folder. This code logins into my account, but it doesn't click Sent folder.
I noticed similar behavior on other websites; whenever a new page loads or refreshes, the bookmarklet stops working.
Why is that and what is the correct way of using the same bookmarklet on different page than it was originally clicked.
Disclaimer: I don't have gmail, so I didn't test this for gmail specifically.
This answer exists to address your comment:
What about iframes. Is theoretically possible to use gmail login in an iframe and therefore when the iframe changes to another page this doesnt have effect on the bookmarklet?
Yes, it is technically possible to have a persistent bookmarklet using iframes (or, deity forbid, a frameset).
As long as your parent window (and it's containing iframe) remain on the same domain, it should work according to cross-domain spec.
It is however possible (depending on used method) to (un-)intentionally 'counter-act' this (which, depending on used counter-action, can still be circumvented, etc..).
Navigate to website, then execute bookmarklet which:
Creates iframe.
Sets onload-handler to iframe.
Replaces current web-page content with iframe (to window's full width and height).
Set iframe's source to current url (reloading the currently open page in your injected iframe).
Then the iframe's onload-handler's job is to detect (using url/title/page-content) what page is loaded and which (if any) actions should be taken.
Example (minify (strip comments and unneeded whitespace) using Dean Edward's Packer v3):
javascript:(function(P){
var D=document
, B=D.createElement('body')
, F=D.createElement('iframe')
; //end vars
F.onload=function(){
var w=this.contentWindow //frame window
, d=w.document //frame window document
; //end vars
//BONUS: update address-bar and title.
//Use location.href instead of document.URL to include hash in FF, see https://stackoverflow.com/questions/1034621/get-current-url-in-web-browser
history.replaceState({}, D.title=d.title, w.location.href );
P(w, d); //execute handler
};
D.body.parentNode.replaceChild(B, D.body); //replace body with empty body
B.parentNode.style.cssText= B.style.cssText= (
F.style.cssText= 'width:100%;height:100%;margin:0;padding:0;border:0;'
) + 'overflow:hidden;' ; //set styles for html, body and iframe
//B.appendChild(F).src=D.URL; //doesn't work in FF if parent url === iframe url
//B.appendChild(F).setAttribute('src', D.URL); //doesn't work in FF if parent url === iframe url
B.appendChild(F).contentWindow.location.replace(D.URL); //works in FF
}(function(W, D){ //payload function. W=frame window, D=frame window document
alert('loaded');
// perform tests on D.title, W.location.href, page content, etc.
// and perform tasks accordingly
}));
Note: one of the obvious methods to minify further is to utilize bracket-access with string-variables for things like createElement, contentWindow, etc.
Here is an example function-body for the payload-function (from above bookmarklet) to be used on http://www.w3schools.com (sorry, I couldn't quickly think of another target):
var tmp;
if(D.title==='W3Schools Online Web Tutorials'){
//scroll colorpicker into view and click it after 1 sec
tmp=D.getElementById('main').getElementsByTagName('img')[0].parentNode;
tmp.focus();
tmp.scrollIntoView();
W.setTimeout(function(){tmp.click()},1000);
return;
}
if(D.title==='HTML Color Picker'){
//type color in input and click update color button 'ok'
tmp=D.getElementById('entercolorDIV');
tmp.scrollIntoView();
tmp.querySelector('input').value='yellow';
tmp.querySelector('button').click();
//click 5 colors with 3 sec interval
tmp=D.getElementsByTagName('area');
tmp[0].parentNode.parentNode.scrollIntoView();
W.setTimeout(function(){tmp[120].click()},3000);
W.setTimeout(function(){tmp[48].click()},6000);
W.setTimeout(function(){tmp[92].click()},9000);
W.setTimeout(function(){tmp[31].click()},12000);
W.setTimeout(function(){tmp[126].click()},15000);
return;
}
above example (inside bookmarklet) minified:
javascript:(function(P){var D=document,B=D.createElement('body'),F=D.createElement('iframe');F.onload=function(){var w=this.contentWindow,d=w.document;history.replaceState({},D.title=d.title,w.location.href);P(w,d)};D.body.parentNode.replaceChild(B,D.body);B.parentNode.style.cssText=B.style.cssText=(F.style.cssText='width:100%;height:100%;margin:0;padding:0;border:0;')+'overflow:hidden;';B.appendChild(F).contentWindow.location.replace(D.URL)}(function(W,D){var tmp;if(D.title==='W3Schools Online Web Tutorials'){tmp=D.getElementById('main').getElementsByTagName('img')[0].parentNode;tmp.focus();tmp.scrollIntoView();W.setTimeout(function(){tmp.click()},1000);return}if(D.title==='HTML Color Picker'){tmp=D.getElementById('entercolorDIV');tmp.scrollIntoView();tmp.querySelector('input').value='yellow';tmp.querySelector('button').click();tmp=D.getElementsByTagName('area');tmp[0].parentNode.parentNode.scrollIntoView();W.setTimeout(function(){tmp[120].click()},3000);W.setTimeout(function(){tmp[48].click()},6000);W.setTimeout(function(){tmp[92].click()},9000);W.setTimeout(function(){tmp[31].click()},12000);W.setTimeout(function(){tmp[126].click()},15000);return}}));
Hope this helps (you get started)!
As JavaScript is executed in the context of the current page only, it's not possible to execute JavaScript which spans over more than one page. So whenever a second page is loaded, execution of the JavaScript of the first page get's halted.
If it would be possible to execute JavaScript on two pages, an attacker could send you to another page, read your personal information there and send it to another server in his control with AJAX (e.g. your mails).
A solution for your issue would be to use Selenium IDE for Firefox (direct link to the extension). Originally designed for automated testing, it can also be used to automate your browser.

Is it possible to run the injected script without reload?

I did a simple auto form filler, by sending info from a created html to the background and then the content script, so the injected script can change the info on the form.
I know the content script run once the page is load. I want to know if I can run the content script again, without the need of reloading the page.
I got sendRequest function in the content script, that I use to make sure it gets the info, only when the page is ready. It then add the info to the form, and wait for me to send it.
In the content script, I added a onRequest and it works (it get the info). but, I don't see the changes on the form, unless I am realoding the page.
I want to know if it is possible to do and if it does what subjects should I learn to implent this.
I am new to chrome extentions and I am still learning :)
in 1 of the pages, I use jQuery, so an answer with jQuery would be good too.
i found out that if we create a chrome.tabs.sendRequest from background we can use chrome.extestion.onRequest from content script and it will execute every time becuse they both run allmost in the same time.
so i did from background:
chrome.tabs.query({}, function (tabs) {
for (var i = 0; i < tabs.length; i++) {
chrome.tabs.sendRequest(tabs[i].id, {...requests u want to send }, function (response) {
});
}
});
from content script:
chrome.extension.onRequest.addListener(function (request, sender, sendRespons) {
//get requested info here
//call functions.
sendResponse({}); //send info back to background page.
});
form's target could be an iframe which would avoid page reload. not sure how useful it'd be.
The correct way to execute a content script again is by using the chrome.tabs.executeScript method. It receives two arguments. The first argument is the tabId, which can be obtained in many ways, such as one of the chrome.tabs events. Use null to execute the content script in the currently selected tab (caution: this may also be an active dev tools window!).
Examples:
// Reloads the current tab
chrome.tabs.executeScript(null, {code:'location.reload();'});
// Executes contentscript.js in the current tab
chrome.tabs.executeScript(null, {file:'contentscript.js'});
// Executes contentscript.js in all frames in the current tab
chrome.tabs.executeScript(null, {file:'contentscript.js', allFrames: true});
// Receives message from content script, and execute a content script:
chrome.extension.onMessage.addListener(function(details) {
if (details.message === 'load a content script') {
chrome.tabs.executeScript(details.sender.tab.id, {file: 'a_script.js'});
}
});
// The previous one is activated from a content script, as follows:
chrome.extension.sendMessage('load a content script');
(onMessage and sendMessage have to be used instead of onRequest and sendRequest, since Chrome 20)

How to pass values to new tab opened by chrome.tabs.create?

I am new to writing extensions for Chrome. I am trying to write a simple extension that will open a new tab with the specified url, on a click of the extension icon and need to pass a value to it so that this value is filled in the input area (ex: input for search) of the specified url.
I am successful in opening the new tab with the given url on clicking the icon. I used background script to listen for the event on the icon and open a tab, the script is as follows:
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.create({'url': 'www.google.com'}, function(tab1) {
// Tab opened.
});
});
Now I am confused about what method will allow me to send some values to the new tab and use the value and perform some operation there like, if I pass "java api" I have to put this in the search area of the google page. I tried looking the Chrome extension docs but it is confusing as to what to use?
You should use chrome.tabs.executeScript() to run a content script in this tab:
chrome.tabs.create(..., function(tab1) {
chrome.tabs.executeScript(tab1.id, {file: ...});
});
This content script will then be able to do something with the tab contents. If it needs some data from your extension it will have to send a message.

Pass variables to current tab via chrome extension

I am writing my first chrome extension, and I want to pass a variable to the currently opened tab and manipulate the DOM with it.
My extension has a button, and when clicked, is executing this code:
chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.executeScript(tab.id, {
file: 'tabscript.js'
});
});
This works fine, but I see no way to pass a variable to tabscript.js so it can be used on the opened tab.
What do you need to pass a variable in to? Do you have a function you are calling in your script?
It must be noted that you don't have access to the pages Javascript, just the DOM.
If you have a particular function that you have to call with specific parameters then you should investigate content scripts and message passing.
Content scripts can get run on every page load (or a selection of pages), and you would use message passing to send a message from your extension button to the function in the content script.
Alternativly, and closer to your original idea you can construct the function you want to call at run time using the following:
chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.executeScript(tab.id, {
code: 'function(){ ...... your code built dynamically ......}'
});
});

Categories