问题
How do I modify DOM html page from background script? The html page exists in the extension's root folder. When then page is opened the URL is looked like "chrome-extension://hffffemnacblbojccelnkhnafndfkhgc/block.html"
File tree in my extension:
css/
bootstrap-theme.css
bootstrap-theme.css.map
bootstrap-theme.min.css
bootstrap.css
bootstrap.css.map
bootstrap.min.css
popup.css
fonts/
img/
128-128.png
1413232635_virus detected 2.png
16-16.png
48-48.png
js/
block.js
bootstrap.js
bootstrap.min.js
event.js
jquery-1.11.1.js
jquery.cookie.js
block.html
manifest.json
popup.html
manifest.json
{
"manifest_version": 2,
"name": "Viper Security ATD",
"version": "1.0",
"description": "Viper Security Advance Threat Defence.",
"icons": {
"48": "img/48-48.png",
"128": "img/128-128.png"
},
"browser_action": {
"default_icon": "img/16-16.png",
"default_title": "Viper Security Advance Threat Defence",
"default_popup": "popup.html"
},
"background": {
"scripts": ["js/jquery-1.11.1.js","js/event.js"],
"persistent": true
},
"permissions": [
"<all_urls>",
"tabs",
"webNavigation"
]
}
回答1:
I want Modify dom of a HTML page of my extension from background javascript. The page exists on my extension's root. the page url looking like:chrome-extension://hffffemnacblbojccelnkhnafndfkhgc/block.html
Technically, you can do that.
If the page with block.html
is open, the background page can get a reference to its window
object with this code:
var win = chrome.extension.getViews("tab").filter(
function(w) {return w.location.pathname == "/block.html"}
)[0];
win.document.getElementById("foo").value("bar"); // Modify that page
win.somefunc(); // Call a global function in that page
// etc.
It is probably cleaner, however, to use Messaging and send messages from the background script that will be received by every block.html
open.
Note: you can't modify the actual files, you can only modify the DOM of an opened document.
来源:https://stackoverflow.com/questions/26409377/modifying-dom-of-a-html-page-from-background-javascript