开发者

Chrome Extension to change innerText using Content Script

I 开发者_C百科want to change the text of a h2 on a page using a Chrome extension using a content script I have the extension set up and I have a script.js file that is being loaded for my content script.

script.js

document.getElementById('texttochange').innerText = "CHANGED !";

However I am always getting the error:

Uncaught TypeError: Cannot set property 'innerText' of null

Is there something extra that needs to be done for Chrome Extensions, this works fine if loaded as a user.js userscript and letting Chrome install install it, this makes me think its a minifest issue however I do not know what I'm missing?

manifest.json
{
  "name": "Test",
  "version": "0.1",
  "description": "Test",
  "icons": { "16": "icon16.png",
             "48": "icon48.png",
             "128": "icon128.png" },
  "content_scripts": [
    {
      "matches": ["http://example.com"],
      "all_frames": true
    }
  ]
}

I could not add a comment as my browser cache got cleared.

The structure is:

<frameset>
    <frame>
    ...
        <h2 id="texttochange">This should change</h2>
    ...
    </frame>
</frameset>

Here is the link te the extension, it is very simple, and in this case it is trying to change a h2 on the site omegle.com which is using the frameset, frame thing from above.


try this-

document.body.innerHTML = document.body.innerHTML.replace(new RegExp("texttochange", "g"),"CHANGED !");
document.head.innerHTML = document.head.innerHTML.replace(new RegExp("texttochange", "g"),"CHANGED !");

and

{
"name": "My First Extension",
"version": "1.0",
"description": "The first extension that I made.",
"background_page": "background.html",
"browser_action": {
  "default_icon": "icon.png",
  "default_popup": "popup.html" 
},
"permissions": [
  "tabs", "http://*/" ]
}  

this is my manifest. The code I posted was in background.html and ran on chrome.tabs.onUpdated just in case the script part might be causing it to not work for some reason


Are you getting this error because your script is injected before DOM load. So, the h2 element that you are trying to change don't exist yet. Just add "run_at": "document_end" in your content_script section then it should work.

manifest.json

{
  "name": "Test",
  "version": "0.1",
  "description": "Test",
  "icons": { "16": "icon16.png",
             "48": "icon48.png",
             "128": "icon128.png" },
  "content_scripts": [
    {
      "matches": ["http://site.com"],
      "run_at": "document_end",
      "js": ["script.js"]
    }
  ]
}

script.js

document.getElementById('h2Id').innerText = "CHANGED !";
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜