我正在尝试制作一个 Chrome 扩展程序,以更改网页中出现的所有名称。 (例如,如果页面包含“that”一词,则会将其更改为另一个名称)。
这个想法是在用户单击浏览器按钮时进行此更改。
我的问题是它没有做出改变!我不知道我做错了什么。
这是 list .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
}
这是背景.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)
您的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 URL 的 "matches": ["http://www.facebook.com/*"],
完全注入(inject)了脚本,而不是 Programmatic injection ,所以它有效,不是因为没有 browser action在你的manifest.json中
{
"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"
}
]
}
如果您需要更多信息,请告诉我。
关于dom - Chrome 扩展程序可在用户单击浏览器按钮时更改 DOM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13673416/