How Can I Run This Script When The Tab Reloads (chrome Extension)?
Solution 1:
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.
Solution 2:
content_scripts
are run at every page (re)load, so it's best to just use those to detect it.
This way you also don't risk running any code in the background
before your content_script
is ready to receive any message.
Solution 3:
2021
If you want to detect reload from background.js in manifest 3 (maybe also 2), chrome.tabs.onUpdated approach didn't work for me :/ It was invoked too many times.
That what worked for me in the end!
// --- On Reloading or Entering example.com ---
chrome.webNavigation.onCommitted.addListener((details) => {
if (["reload", "link", "typed", "generated"].includes(details.transitionType) &&
details.url === "http://example.com/") {
codeAfterReload();
// If you want to run only when the reload finished (at least the DOM was loaded)
chrome.webNavigation.onCompleted.addListener(functiononComplete() {
codeAfterReloadAndFinishSomeLoading();
chrome.webNavigation.onCompleted.removeListener(onComplete);
});
}
});
For more transition types: https://developer.chrome.com/docs/extensions/reference/history/#transition_types
good luck :)
Post a Comment for "How Can I Run This Script When The Tab Reloads (chrome Extension)?"