如何使用 chrome 扩展检测 url 的变化?

met*_*ain 1 html javascript google-chrome-extension

我正在学习制作 chrome 扩展。我遇到了一个问题,当alert("test");onload 未激活时,我想要运行的上下文脚本(即使只是)也无法运行。当您按后退箭头访问上次访问的页面时,也会发生这种情况。我注意到网址发生了变化,但没有任何激活。我如何检测到这一点?如果答案是服务人员,那么详细的解释将不胜感激。

Sam*_*eth 5

迈菲斯特2.0版本


尝试使用chrome.tabs.onUpdated.addListener((id, change, tab)=>{}). 每次 URL 更改时都应该运行!下面是一些代码的简约示例,当 URL 更改时,将 js 注入到站点。

背景.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'
    });
});
Run Code Online (Sandbox Code Playgroud)

主要版本3.0


您可以通过使用来做到这一点chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {})。但是,当页面 URL 更改时,这实际上会触发多次,因此您需要在changeInfo 变量中添加对 URL 的检查,因此它只触发一次!

清单.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"
    }
}
Run Code Online (Sandbox Code Playgroud)

背景.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);

    }
});
Run Code Online (Sandbox Code Playgroud)

注入.js:

// you can write the code here that you want to inject
alert('Hello world!');
Run Code Online (Sandbox Code Playgroud)