Friday, May 10, 2024
11
rated 0 times [  13] [ 2]  / answers: 1 / hits: 22383  / 11 Years ago, wed, june 5, 2013, 12:00:00

So i'd like to run a script when the tab reloads in a specified URL. It almost works, but actually id doesn't :)
This is my manifest file:



{
manifest_version: 2,

name: Sample Extension,
description: Sample Chrome Extension,
version: 1.0,

content_scripts:
[
{
matches: [http://translate.google.hu/*],
js: [run.js]
}
],

permissions:
[
activeTab,
tabs
],

browser_action:
{
default_title: Sample,
default_icon: icon.png
}
}


and this is run.js:



chrome.tabs.onUpdated.addListener(
function ( tabId, changeInfo, tab )
{
if ( changeInfo.status === complete )
{
chrome.tabs.executeScript( null, {file: program.js} );
}
}
);


The programs.js just alerts some text (yet). When I put an alert to the first line of the run.js, it alerts, but when I put it in the if, it doesn't. I can't find the problem. Did I type something wrong?


More From » google-chrome-extension

 Answers
18

Assuming that http://translate.google.hu/* pages are the ones you wish to inject code into on reload, you would have to go about it in a slightly different way. Currently you are always injecting code into those pages (without the permission to do so, no less) and then trying to use the chrome.tabs api inside that content script, which you can't do. Instead, we will put the listener in a background page and inject the code only on a page refresh, like you want. First the manifest:



{
manifest_version: 2,
name: Sample Extension,
description: Sample Chrome Extension,
version: 1.0,
background: {
scripts: [background.js]
},
permissions:[
http://translate.google.hu/*, tabs
]
}


background.js



chrome.tabs.onUpdated.addListener(function(tabId,changeInfo,tab){
if (tab.url.indexOf(http://translate.google.hu/) > -1 &&
changeInfo.url === undefined){
chrome.tabs.executeScript(tabId, {file: program.js} );
}
});


This will listen for the onUpdated event, checks if it is one of the url's that we want to inject into, and then it checks if the page was reloaded. That last step is accomplished by checking if changeInfo.url exists. If it does, then that means that the url was changed and thus not a refresh. Conversely, if it doesn't exist, then the page must have only been refreshed.


[#77788] Tuesday, June 4, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
chazw

Total Points: 127
Total Questions: 129
Total Answers: 92

Location: Sao Tome and Principe
Member since Wed, Dec 21, 2022
1 Year ago
;