我正在试图弄清楚如何编写一个简单的Chrome扩展程序,它允许将网页从一个字母表音译到另一个字母表。不幸的是,谷歌关于Chrome扩展程序的文档对初学者来说非常困惑。我在这里看到了很多类似的问题,f.ex。 Replace text in website with Chrome content script extension,但仍然无法说清楚。在试运行中,我试图用“Z”替换页面中的所有“a”。
这是我的Manifest.json:
{
"name": "My Chrome extension",
"version": "0.1",
"browser_action": {
"default_icon": "icon.png"
},
"permissions": [
"tabs", "http://*/*", "https://*/*"
],
"content_scripts": [{
"matches": ["http://*/*", "https://*/*"],
"js": ["myscript.js"]
}]
}
Myscript.js:
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript(
null, {code:"document.body.innerHTML = document.body.innerHTML.replace(new RegExp("a", "g"), "Z")"});
});
但这无法奏效。如果我只在Myscript.js中包含一行:
document.body.innerHTML = document.body.innerHTML.replace(new RegExp("a", "g"), "Z");
然后,一旦页面加载,所有'a'字母都会被'Z'替换,但这不是我的目标,因为我只想在按下扩展按钮后才能使它工作。
非常感谢任何帮助。
答案 0 :(得分:1)
您已设置扩展程序以使用内容脚本注入代码。内容脚本将被注入到与您的匹配字段匹配的任何页面中。你想要的只是在他们点击你的浏览器动作时才注入脚本。为此,您可以拥有一个侦听chrome.browserAction.onClicked事件的背景页面并对其做出反应。或者你可以有一个浏览器操作的默认页面,它将代码注入到页面中,如果你的put window.close作为脚本的一部分,这将阻止任何弹出窗口发生,并允许你避免使用后台页面(我很大)尽可能避免使用背景页面。
有关第一种方法的示例,请查看此示例....
http://src.chromium.org/viewvc/chrome/trunk/src/chrome/common/extensions/docs/examples/api/browserAction/make_page_red/
这是第二种方法的示例(这是set_page_color示例的修改版本)...
的的manifest.json 强>
{
"name": "A browser action that changes the page color.",
"version": "1.0",
"permissions": [
"tabs", "http://*/*", "https://*/*"
],
"browser_action": {
"default_title": "Set this page's color.",
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"manifest_version": 2
}
<强> popup.html 强>
<!doctype html>
<html>
<head>
<script src="popup.js"></script>
</head>
<body>
</body>
</html>
<强> popup.js 强>
chrome.tabs.executeScript(null,{file:"injectedCode.js"});
window.close();
injectCode.js
// This was just a quick look at changing text on a page
// there could be more tags you should ignore and there could be a better way of doing this all together
var ignoreTags = ["NOSCRIPT","SCRIPT","STYLE"];
var nodeIterator = document.createNodeIterator(
document,
NodeFilter.SHOW_TEXT,
function (node){
var parentTag = node.parentNode.tagName.toUpperCase();
if ( ignoreTags.indexOf(parentTag)==-1 ) {return true} else {return false};
},
false
);
var node;
while ( (node = nodeIterator.nextNode()) ) {
node.data = node.data.replace(/a/g, 'z');
}
注意强>
正如Rob W在评论中指出chrome.tabs
和chrome.browserAction
在内容脚本中无法使用,这就是必须在后台页面中使用chrome.browserAction.onClicked
的原因。
答案 1 :(得分:0)
myscript.js
中的代码是注入页面的内容。它当前设置的方式不起作用,因为您自动将注入的代码注入到每个页面中以选择页面。您需要将myscript.js
代码移动到background_page
,然后只有在单击按钮时才会注入。{/ p>
https://code.google.com/chrome/extensions/background_pages.html