2

我正在尝试构建 chrome 插件,我需要在其中捕获在网页上触发的所有网络请求。我已经浏览了 Docs @ http://developer.chrome.com/extensions/devtools_network.html

我正在使用

    chrome.devtools.network.getHAR(
    function(harLog) {
        alert(harLog.entries.length);

});

但每次我得到 0 个条目时,即使我尝试先打开面板并刷新网页。如果我有什么遗漏,有人可以帮忙吗??

我正在使用任何网页来测试这个,例如“ http://www.cnn.com/ ”并在清单中设置权限为

"permissions": [
    "http://*/*",
    "https://*/*"
  ]
4

2 回答 2

4

您可以侦听请求并根据tabId字段进行过滤。当然,您需要跟踪活动选项卡(每个窗口一个选项卡)。
例如:

  1. 使用chrome.tabs.onActivated监听每个窗口的活动选项卡中的更改并将其存储tabId在本地变量中。

  2. 使用chrome.windows.onRemoved停止跟踪关闭窗口的选项卡。

  3. 为适合您目的的任何chrome.webRequest.*事件注册侦听器。例如,要在请求准备好发送后立即在其中一个活动选项卡中获得任何请求的通知,请为chrome.webRequest.onBeforeRequest注册一个侦听器。


下面是一个完全做到这一点的示例扩展的源代码。

清单.json:

{
    "manifest_version": 2,
    "name":    "Test Extension",
    "version": "0.0",
    "offline_enabled": false,

    "background": {
        "persistent": true,
        "scripts": ["background.js"]
    },

    "permissions": [
        "webRequest",
        "*://*/*"
    ]
}

背景.js:

/* Keep track of the active tab in each window */
var activeTabs = {};

chrome.tabs.onActivated.addListener(function(details) {
    activeTabs[details.windowId] = details.tabId;
});

/* Clear the corresponding entry, whenever a window is closed */
chrome.windows.onRemoved.addListener(function(winId) {
    delete(activeTabs[winId]);
});

/* Listen for web-requests and filter them */
chrome.webRequest.onBeforeRequest.addListener(function(details) {
    if (details.tabId == -1) {
        console.log("Skipping request from non-tabbed context...");
        return;
    }

    var notInteresting = Object.keys(activeTabs).every(function(key) {
        if (activeTabs[key] == details.tabId) {
            /* We are interested in this request */
            console.log("Check this out:", details);
            return false;
        } else {
            return true;
        }
    });

    if (notInteresting) {
        /* We are not interested in this request */
        console.log("Just ignore this one:", details);
    }
}, { urls: ["<all_urls>"] });

/* Get the active tabs in all currently open windows */
chrome.tabs.query({ active: true }, function(tabs) {
    tabs.forEach(function(tab) {
        activeTabs[tab.windowId] = tab.id;
    });
    console.log("activeTabs = ", activeTabs);
});
于 2013-11-21T09:39:07.157 回答
0

在阅读 HAR 之前,您需要等待页面下载完成。尝试这样的事情:

var interval = setInterval( function() {
                   clearInterval(interval);
                   chrome.devtools.network.getHAR(
                          function(harLog) {
                              alert(harLog.entries.length);
                          });               
                    }, 5000 );

这将在读取 HAR 之前等待 5 秒。

于 2015-08-01T01:08:26.373 回答