简体   繁体   中英

Chrome Extension - Append to page when url changes

I am working on a chrome extension that will listen to a url change on a domain, and when the url matches a pattern, append some HTML to the DOM.

My manifest.json looks like so:

{
    "name": "Append to DOM",
    "description": "Testing",
    "version": "1",
    "manifest_version": 2,
    "content_scripts": [
        {
            "matches": [
                "http://www.somedomain.com/*"
            ],
            "js": [
                "content.js"
            ]
        }
    ],
    "permissions": ["tabs", "activeTab"]
}

and content.js looks like so:

chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
    if (changeInfo.url == 'http://www.somedomain.com/matching-pattern') {
        var myDiv = document.createElement("div");
        myDiv.innerHTML = 'SAMPLE HTML';
        document.body.appendChild(myDiv);
    }
});

However, the listener does not fire (and the div not appended) when the url is updated.

Any help is appreciated.

Content scripts don't have access to chrome.tabs You can use chrome.tabs in the background script

In order to handle change of URL in the content script the cheapest solution that always works - use setInterval

var prevURL = '';
setInterval(function() {
    if (document.location.href != prevURL) {
        // do something
        prevURL = document.location.href;
    }
}, 1000);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM