Search code examples
javascripthtmlgoogle-chrome-extension

How do you detect changes in url with a chrome extension?


I am learning to make chrome extensions. I ran into a problem where context scripts that I want to run, even just alert("test");, are unable to when onload is not activated. This also occurs when you press the back arrow to visit the last visited page. I notice that the url changed, but nothing activates. How do I detect this? If the answer is with service workers, a detailed explanation would be greatly appreciated.


Solution

  • manifest version 2.0


    Try using chrome.tabs.onUpdated.addListener((id, change, tab)=>{}). This should run every time the URL changes! Here is a minimalistic example of some code that injects js to a site when the URL changes.

    background.js:

    // inject code on change
    chrome.tabs.onUpdated.addListener((id, change, tab) => {
    
        // inject js file called 'inject.js'
        chrome.tabs.executeScript(id, {
            file: 'inject.js'
        });
    });
    

    manifest version 3.0


    You can do this by using chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {}). However, this will actually trigger multiple times when a page URL is changed. So you need to add a check for the URL in the changeInfo variable to only trigger once.

    manifest.json:

    {
        "name": "URL change detector",
        "description": "detect a URL change in a tab, and inject a script to the page!",
        "version": "1.0",
    
        "manifest_version": 3,
        "permissions": [
            "scripting",
            "tabs"
        ],
        "host_permissions": [
            "http://*/*",
            "https://*/*"
        ],
    
        "background": {
            "service_worker": "background.js"
        }
    }
    

    background.js:

    // function that injects code to a specific tab
    function injectScript(tabId) {
    
        chrome.scripting.executeScript(
            {
                target: {tabId: tabId},
                files: ['inject.js'],
            }
        );
    
    }
    
    // adds a listener to tab change
    chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
    
        // check for a URL in the changeInfo parameter (url is only added when it is changed)
        if (changeInfo.url) {
            
            // calls the inject function
            injectScript(tabId);
    
        }
    });
    

    inject.js:

    // you can write the code here that you want to inject
    alert('Hello world!');