我正在尝试编写一个简单的 Chrome pageAction 扩展,以将页面上的所有 anchor 从一个域更改为另一个域...但我似乎无法让它正常工作,而且我在调试它时遇到了麻烦.
我是否误解了如何构建这种扩展?或者我只是滥用 API?
manifest.json:
{
"name": "theirs2ours",
"version": "1.0",
"description": "Changes all 'their' URLs to 'our' URLs.",
"background_page": "background.html",
"permissions": [
"tabs"
],
"page_action": {
"default_icon": "cookie.png",
"default_title": "theirs2ours"
},
"content_scripts": [
{
"matches": ["http://*/*"],
"js": ["content.js"]
}
]
}
背景.html:
<html>
<head>
<script type='text/javascript'>
chrome.tabs.onSelectionChanged.addListener(function(tabId) {
chrome.pageAction.show(tabId);
});
chrome.tabs.getSelected(null, function(tab) {
chrome.pageAction.show(tab.id);
});
chrome.pageAction.onClicked.addListener(function(tab) {
chrome.tabs.sendRequest(tab.id, {}, null);
});
</script>
</head>
<body>
</body>
</html>
content.js:
var transform = function() {
var theirs = 'http://www.yourdomain.com';
var ours = 'http://sf.ourdomain.com';
var anchors = document.getElementsByTagName('a');
for (var a in anchors) {
var link = anchors[a];
var href = link.href;
if (href.indexOf('/') == 0) link.href = ours + href;
else if (href.indexOf(theirs) == 0) link.href = href.replace(theirs, ours);
}
};
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
transform();
});
最佳答案
我认为这不是实现您想要的扩展的方式。
首先,我假设您想在单击页面操作按钮时替换 anchor 。
无论您是否单击页面操作按钮,您的 list 都会在每个页面上注入(inject) content.js。
我建议您从 list 中删除 content_scripts 字段,并手动注入(inject) content.js,
chrome.tabs.executeScript(tabId, {file:'content.js'})
您应该在页面操作的点击监听器中执行此操作。
顺便说一句,在该监听器中,您正在向内容脚本发送请求,但它没有监听器来监听此类请求消息。在此扩展中,您不需要使用 senRequest。
关于google-chrome-extension - 简单的 Chrome pageAction 扩展不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9628579/