2012-03-09 66 views
2

我想写一个微不足道的Chrome页面扩展,将一个页面上的所有锚点从一个域更改为另一个域......但我似乎无法完成它的工作,在调试时遇到麻烦。微小的Chrome页面扩展不起作用

我是否误解了这种扩展需要如何构建?或者我只是滥用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"] 
    } 
    ] 
} 

background.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(); 
}); 
+0

注证明的API已经通过名称和签名变了 - 今天有同样的效果,你需要['chrome.tabs.onActivated'(http://developer.chrome.com/extensions/tabs。 html#event-onActivated)和['chrome.tabs.getCurrent'](http://developer.chrome.com/extensions/tabs.html#method-getCurrent)。 – Ronny 2013-06-13 11:01:52

回答

2

你不是requesting permission在这些页面上运行内容脚本。内容脚本的匹配决定了它们在哪个页面中执行,但仍需要请求将脚本插入这些页面的权限。

"permissions": [ 
    "tabs", 
    "http://*/*" 
] 
+0

就在当场。谢谢! – 2012-03-12 02:48:02

3

我觉得这是不做你想要的扩展的方式。

首先,我假设你想在点击页面动作按钮时替换锚点。

无论您是否点击页面动作按钮,您在每个页面上注册的清单content.js

我建议你从你的清单中删除的content_scripts领域,并注入content.js手动,与

chrome.tabs.executeScript(tabId, {file:'content.js'}) 

你应该在页面动作的点击监听器做到这一点。

顺便说一下,在该侦听器中,您正在向内容脚本发送请求,但它没有侦听器来侦听此类请求消息。在此扩展中,您不需要使用senRequest

+1

很好的建议。总的来说,我认为我只需要对API更熟悉一点。 – 2012-03-12 02:48:42