从背景javascript修改html页面的DOM

时间:2014-10-16 16:25:39

标签: google-chrome google-chrome-extension google-chrome-devtools

如何从后台脚本修改DOM html页面? html页面存在于扩展程序的根文件夹中。当页面打开时,URL看起来像" chrome-extension://hffffemnacblbojccelnkhnafndfkhgc/block.html"

我的扩展程序中的文件树:

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 个答案:

答案 0 :(得分:2)

  

我想从后台javascript修改我的扩展程序的HTML页面的dom。该页面存在于我的扩展程序的根目录中。页面网址看起来像:chrome-extension://hffffemnacblbojccelnkhnafndfkhgc/block.html

从技术上讲,你可以做到这一点。

如果打开了block.html的网页,则后台网页可以使用this code获取对其window对象的引用:

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.

然而,使用Messaging并从每个block.html打开的后台脚本发送消息可能更干净。

注意:您无法修改实际文件,只能修改已打开文档的DOM。