简体   繁体   中英

Chrome extension: Javascript not loading

I have the following code for a chrome extension, the contentscript.py as per another question on stackoverflow:

manifest.js

{
"name": "test script",
"version": "0.1",
"content_scripts": [{
    "js": ["contentscript.js"],
    "matches": ["http://*/*"]
}],
"manifest_version": 2,
"web_accessible_resources": ["script.js"]
}

contentscript.js

var s = document.createElement('script');
s.src = chrome.extension.getURL('script.js');
(document.head||document.documentElement).appendChild(s);
s.onload = function() {
    s.parentNode.removeChild(s);
};

script.js

document.body.innerHTML = document.body.innerHTML.replace(new RegExp("this", "gi"), "that");

In order to simply replace some text. If I put the same expression that is on script.js on a test html file, it works, but it in the extension it doesn't appear as though the code is actually injected. I cannot for the life of me figure out why. The manifest and the contentscript seem in order, so I don't know what to do here.

try adding "https://*/*" to matches in manifest.json. I recommend you to put this first line in your contentscript.js:

console.log('Content script loaded and started');

So you can inspect the page (F12, console tab) and see if the content script was injected or not. It'll help a lot with your debugging.

I don't know what is going on in your script.js, but it worth consider that your removechild in the onload event may occur before your task being done.

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