有很多选择,一个比另一个更复杂。
-
webRequest API,特别是onBeforeRequest event。 (更好的是,即将推出的declarativeWebRequest API)。
-
Content scripts。在页面中注入
location.replace('http://example.com')。
-
tabs API。使用onUpdated event 检测页面何时更改其位置,使用chrome.tabs.update 更改其URL。不过要避免无限循环!
第一个是最好的,因为它在页面被请求之前就被激活了。第二个可以在请求完成后激活,但在页面呈现之前 ("run_at":"document_start") 或在页面呈现之后 ("run_at":"document_end")。为了完整起见,我提到了最后一个,但您不应该使用它,因为其他选项要好得多。
这是一个使用 webRequest API 的示例,这是一个简单的扩展,它允许我浏览 Pirate bay 上的页面,即使主要主机已被我的 ISP 删除(实际的 URL 列表要长得多,但我为了示例而省略了它们)。
有关 URL 格式的说明,请参阅 match patterns。
manifest.json
{
"name": "The Pirate Bay",
"description": "Redirect The Pirate Bay to a different host",
"version": "1.0",
"manifest_version": 2,
"background": {"scripts":["background.js"]},
"permissions": [
"webRequest",
"*://thepiratebay.se/*",
"*://www.thepiratebay.se/*",
"webRequestBlocking"
]
}
background.js
var host = "http://tpb.pirateparty.org.uk";
chrome.webRequest.onBeforeRequest.addListener(
function(details) {
return {redirectUrl: host + details.url.match(/^https?:\/\/[^\/]+([\S\s]*)/)[1]};
},
{
urls: [
"*://piratebay.se/*",
"*://www.piratebay.se/*"
],
types: ["main_frame", "sub_frame", "stylesheet", "script", "image", "object", "xmlhttprequest", "other"]
},
["blocking"]
);