为什么chrome.webRequest.OnBeforeRequest在chrome.webNavigation.onBeforeNavigate之前触发?

时间:2015-07-16 22:46:47

标签: google-chrome-extension

我试图理解逻辑。在我看来,onBeforeNavigate事件应该在我们听到任何请求之前完成。但我发现onBeforeRequest事件首先发生。这里的示例代码将展示我的意思。

test.js

function Test(url) {
  chrome.tabs.create({ url: "" }, function (tab) {
    chrome.webNavigation.onBeforeNavigate.addListener(function (details) {
      console.log("chrome.webNavigation.onBeforeNavigate hit on " + details.timeStamp);
    });

    chrome.webRequest.onBeforeRequest.addListener(function (details) {
      console.log("chrome.webRequest.onBeforeRequest hit on " + details.timeStamp);
    }, {
      tabId: tab.id,
      urls: ["<all_urls>"]
    });

    chrome.tabs.update(tab.id, {
      url: url
    });
  });
}
Test("http://www.steam.com");    // Simple url with only two requests

产生的控制台消息:

chrome.webRequest.onBeforeRequest hit on 1437083141916.896
chrome.webNavigation.onBeforeNavigate hit on 1437083141916.906
chrome.webRequest.onBeforeRequest hit on 1437083141940.385

的manifest.json

{
  "background": {
    "persistent": true,
    "scripts": [
      "test.js"
    ]
  },
  "manifest_version": 2,
  "name": "Test",
  "permissions": [
    "<all_urls>",
    "webNavigation",
    "webRequest"
  ],
  "version": "1.0"
}

以下是三个details的视图,按照事件发生的顺序:

// first chrome.webRequest.onBeforeRequest
{
  "frameId" : 0,
  "method" : "GET",
  "parentFrameId" : -1,
  "requestId" : "72285",
  "tabId" : 1312,
  "timeStamp" : 1437083141916.896,
  "type" : "main_frame",
  "url" : "http://www.steam.com/"
},

// chrome.webNavigation.onBeforeNavigate
{
  "frameId" : 0,
  "parentFrameId" : -1,
  "processId" : 3567,
  "tabId" : 1312,
  "timeStamp" : 1437083141916.906,
  "url" : "http://www.steam.com/"
},

// second chrome.webRequest.onBeforeRequest
{
  "frameId" : 0,
  "method" : "GET",
  "parentFrameId" : -1,
  "requestId" : "72286",
  "tabId" : 1312,
  "timeStamp" : 1437083141940.385,
  "type" : "image",
  "url" : "http://www.steam.com/images/pipebackwhite.gif"
}

2 个答案:

答案 0 :(得分:4)

如果你考虑每个事件何时开始,这应该是有意义的。

OnBeforeRequest在你向服务器发出请求之前就开始了:

Fires when a request is about to occur. This event is sent before any TCP
connection is made and can be used to cancel or redirect requests.

另一方面,onBeforeNavigate在页面导航到下一页之前触发:

Fired when a navigation is about to occur.

如果您考虑浏览器的工作方式,它会向服务器发出请求,如果是典型的GET,则浏览器会根据标头导航到请求的新页面。但是,这会在实际请求中发生,OnBeforeRequest正在运行之前运行任何内容。

所以,你提出请求,api说:

  • 在我做任何事之前,我会发出请求,我应该开启OnBeforeRequest
  • 好的,我处理了这个请求,它让我导航/重定向,在我这样做之前,我应该做OnBeforeNavigate

答案 1 :(得分:0)

OnBeforeRequest并不总是在onBeforeNavigate之前触发。在要加载的页面立即执行window.location="example.com"重定向的情况下,首先您将获得onBeforeNavigate事件,然后才是onBeforeRequest

Chrome API文档指出没有定义的顺序:

  

webRequest API的事件与webNavigation API的事件之间没有定义的顺序。”