Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 956
András Geiszl Avatar asked Jun 05 '13 21:06

András Geiszl


People also ask

How do you reload a Chrome extension?

1 - The extension's toolbar button. 2 - Browsing to "http://reload.extensions". The toolbar icon will reload unpacked extensions using a single click.

How do I stop Chrome from reloading?

When you click on the tab next time, it loads it again. To prevent this, switch the toggle to X, and Chrome won't refresh specific tabs that you don't want to be refreshed. Additionally, you can copy and paste “chrome://flags/” into Chrome's address bar to open the flags page.


1 Answers

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(function onComplete() {

            codeAfterReloadAndFinishSomeLoading();

            chrome.webNavigation.onCompleted.removeListener(onComplete);
        });
    }
});

For more transition types: https://developer.chrome.com/docs/extensions/reference/history/#transition_types

good luck :)

like image 86
Yam Shargil Avatar answered Oct 16 '22 16:10

Yam Shargil