this is my background.js file
chrome.tabs.onUpdated.addListener(function(tabId,info, tab) {
var sites =new Array('site2','site1');
var url=tab.url;
var siteFlag=0;
for(var i in sites) {
var regexp = new RegExp('.*' + sites[i] + '.*','i');
if (regexp.test(url)) {siteFlag=1;}
};
if(siteFlag==1){
chrome.tabs.executeScript(tabId, {file:"contentscript.js"});
chrome.tabs.executeScript(tabId, {file:"jquery.js"});
chrome.tabs.insertCSS(tabId,{file:"box.css"});
}
});
In the contentscript.js I simply run a popup box.
$(document).ready(function () {
function popup() {...}
if (window.addEventListener)
{
window.addEventListener('load', popup(), false);
}
else if (window.attachEvent)
{
window.attachEvent('onload', popup());
}
});
There are some pages that there are one popup-box and there are pages that two or even more
what is the problem?
=============EDIT==================
those pages contain Iframes
I am not sure why the content scripts load twice. But I had this problem too. I added the following to the "content_scripts" element in manifest.json and it worked just fine.
"content_scripts" : [
{
"all_frames" : false,
"run_at" : "document_end",
}
]
So finally, manifest.json:
{
"name": "ABC",
"version": "0.0.0.1",
"manifest_version": 2,
"key": "longkeyhere",
"description": "Description",
"minimum_chrome_version": "29",
"background": {
"scripts": [
"jquery.js",
"jquery.min.js",
]
},
"content_scripts" : [
{
"all_frames" : false,
"run_at" : "document_end",
"matches" : [ "http://*/*" ],
"js" : [
"jquery.js",
"jquery.min.js",
]
}
],
"options_page": "options.html",
"permissions": [
"http://*/*",
"https://*/*",
"contextMenus",
"tabs",
"identity",
"storage"
]
}
chrome.tabs.onUpdated.addListener
is fired when tab status changes, this has nothing to do with iframes. Your script is injected multiple times to the same frame because you inject it for each status change, and you want to inject it only when status changes to "complete". Modify your code by adding if (changeInfo.status == "complete") {
:
chrome.tabs.onUpdated.addListener(function(tabId,info, tab) {
if (info.status == "complete") {
/* checking & injecting stuff */
}
});
Most likely this is caused by pages using frames. The script gets loaded for each frame. You might be able to detect in which frame you are loaded, or whether one frame already has your script if you absolutely want to execute your script only once.
You can control your content script execution using manifest file of your extension: You can prevent your content script from loading into iframes or a specific set of urls. Here is an sample manifest section:
"all_frames": true,
"js": [ "ContentOnDocStart.js" ],
"matches": [ "http://*/*", "https://*/*" ],
"exclude_matches": [ ],
"run_at": "document_start"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With