簡體   English   中英

您如何使用 chrome 擴展檢測 url 的變化?

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

我正在學習制作 chrome 擴展。 我遇到了一個問題,我想運行上下文腳本,甚至只是alert("test"); , 在未激活 onload 時無法使用。 當您按后退箭頭訪問上次訪問的頁面時,也會發生這種情況。 我注意到 url 發生了變化,但沒有激活。 我如何檢測到這一點? 如果答案是服務人員,將不勝感激詳細的解釋。

maifest 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'
    });
});

主要版本 3.0


您可以使用chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {})來做到這一點。 但是,這實際上會在頁面 URL 更改時觸發多次因此您需要在 changeInfo 變量中添加對 URL 的檢查,因此它只會觸發一次!

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"
    }
}

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

    }
});

注入.js:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM