Geiszla Geiszla - 5 months ago 23
Javascript Question

How can I run this script when the tab reloads (chrome extension)?

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?

Answer

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.