Chrome Extension API v17:webRequest onErrorOccurred.addListener

时间:2012-01-25 17:37:41

标签: redirect google-chrome-extension webrequest

我正在尝试设置类似于http://code.google.com/chrome/extensions/trunk/samples.html#webrequest的chrome扩展名,但是当get请求因任何原因失败时,我们会将onErrorOccurred侦听器重定向到特定的已知页面。

的manifest.json:

{
  "name": "Custom Error",
  "version": "0.1",
  "description": "Redirect all navigation errors to specified location/file.",
  "permissions": [
    "webRequest",
    "tabs",
    "<all_urls>"
  ],
  "background": {
    "page": ["error_listener.html"]
  }
}

error_listener.html:

<!doctype html>
<script>
  chrome.webRequest.onErrorOccurred.addListener(
      function onErrorOccurred(details) {
        console.log('onBeforeRequest ', details.url);
        return { redirectUrl: 'http://www.google.com' }
      }, 
      {urls: ["<all_urls>"]}
      //{urls: ["http://*/*", "https://*/*"]}
  );
        //chrome.tabs.update(details.tabId, {url: "http://www.google.com", ['blocking']});
        //alert("what?");
</script>

扩展加载时没有指出任何错误,但浏览器选项卡未被重定向。我使用Chrome 16和Chrome 17试过这个;使用Chrome 16时,我确实将“chrome.webRequest”更改为“chrome.experimental.webRequest”,并将“experimental”添加到权限列表中。

到目前为止,似乎问题是虽然在查看chrome://扩展时似乎加载了扩展名,但实际上并未加载文件 - 使用Developer Tools时,我看不到对error_listener的任何引用html的。

我还尝试使用以下标志运行Chrome 17:

8611  25/01/12-11:22:05> google-chrome --restore-last-session 
--debug-on-start --log-level=0 --enable-logging 
--enable-extension-activity-logging --enable-extension-alerts 
--debug-plugin-loading --debug-print | tee > log1.txt

显然,我只是在黑暗中用那个命令行探索。任何人都有任何关于如何使这个工作的线索?在此先感谢您的帮助!

2 个答案:

答案 0 :(得分:2)

没有webRequest.onErrorOccurred事件。您可以使用webNavigation.onErrorOccurred。如果您想捕获DNS错误并重定向到另一个URL,您可以使用以下代码:

<script>
chrome.webNavigation.onErrorOccurred.addListener(function(details) 
{
    if (details.frameId != 0) //ignore subframes. 0 is main frame
    { return; }

    chrome.tabs.update(details.tabId, {url: "https://www.google.com/search?q=" + details.url});
});
</script>

答案 1 :(得分:1)

在Chrome 16中,您应该使用:

"background_page": "background.html"

而不是

"background": {
    "page": ["error_listener.html"]
}

这解决了未加载后台页面的问题。与trunk docs相比,current docs中的内容可能已发生变化,我不确定哪个版本的Chrome开始实施新的manifest.json格式。