当用户点击浏览器按钮时,Chrome扩展程序可以更改DOM

时间:2012-12-02 20:18:39

标签: dom google-chrome-extension

我正在尝试对Chrome进行扩展,以更改网页中所有名称的出现。 (例如,如果页面上有“那个”,则会将其更改为其他名称)。

想法是在用户点击浏览器按钮时进行此更改。

我的问题是它没有做出改变!我不知道我做错了什么。

这是manifest.json:

{
  "name": "App Name",
  "description": "App description",
  "version": "1.0",
  "background": {
    "scripts": ["jquery.min.js", "jquery.ba-replacetext.min.js","background.js"]
  },
  "permissions": [
    "tabs", "http://*/*", "https://*/*"
  ],
  "browser_action": {
      "default_title": "App name",
      "default_icon": "icon.png"
  },
  "manifest_version": 2
}

这是background.js:

chrome.browserAction.onClicked.addListener(function(tab) {
    var state = document.readyState;
    var carregou = false;
    var matches = document.body.innerText.match(regex);

if (state == "interactive"|| (!carregou)){
 $("body *").replaceText( /That/gi, "" );
 var regex = /That/gi;
 matches = document.body.innerText.match(regex);
 if(matches){
    alert("Reload the page (f5)");
 }else{ 
    alert("All changes done! :D");
    carregou = true;
 }
}
});

我做了一个更改页面而没有点击浏览器按钮,它可以工作。这是代码:

{
  "name": "App Name",
  "version": "1.0",
  "manifest_version": 2,
  "description": "App description.",
  "content_scripts": [
   {
   "matches": ["http://www.facebook.com/*"],
   "js": ["jquery.min.js","jquery.ba-replacetext.min.js", "script.js"],
   "run_at": "document_end"
   }
   ]
}

sript.js:

var state = document.readyState;
var carregou = false;
var matches = document.body.innerText.match(regex);
if (state == "interactive"|| (!carregou)){
 $("body *").replaceText( /That/gi, "" );
 var regex = /That/gi;
 matches = document.body.innerText.match(regex);
 if(matches){
    alert("Reload the pahe (f5)");
 }else{ 
    alert("All changes done! :D");
    carregou = true;
 }
}

Chrome版本:Windows 7上的23.0.1271.95 m 谢谢!

1 个答案:

答案 0 :(得分:2)

案例1)

您的background.js在其own generated html page世界中执行代码A s the architecture overview explains,后台页面是在扩展程序中运行的HTML页面。它存在于您的扩展的生命周期中,并且一次只有一个实例处于活动状态。

因此,所有代码都试图更改background.html页面中所有名称的出现

您可以使用相同的代码

使用Programmatic injection来实现您的功能

<强>示范

/* in background.html */
chrome.browserAction.onClicked.addListener(function(tab) {
  chrome.tabs.executeScript(null,
                           {code:"document.body.bgColor='red'"});
});

案例2)

您已为所有Facebook网址"matches": ["http://www.facebook.com/*"],而不是Programmatic injection完全注入了脚本,因此它有效,而不是因为您的manifest.json中没有browser action

{
  "name": "App Name",
  "version": "1.0",
  "manifest_version": 2,
  "description": "App description.",
  "content_scripts": [
   {
   "matches": ["http://www.facebook.com/*"],
   "js": ["jquery.min.js","jquery.ba-replacetext.min.js", "script.js"],
   "run_at": "document_end"
   }
   ]
}

如果您需要更多信息,请与我们联系。