Chrome 访问网络请求和响应[重复]

dxxyhpgq  于 12个月前  发布在  Go
关注(0)|答案(1)|浏览(157)

此问题已在此处有答案

Chrome extension to read HTTP response(2个答案)
Chrome Extension - How to get HTTP Response Body?(5个答案)
上个月关门了。
我试图从网页上获取所有的子资源或URL或fetch/xhr(我希望我能很好地沟通)。
我试过使用Chrome.webRequest API,但它没有得到页面上调用的所有子资源/fetch/xhr,不像我尝试使用chrome.debugger,它得到了我想要的,请允许我展示代码。

chrome.webRequest.onBeforeRequest.addListener(
    (details) => {
        console.log("all resource URL:", details.url, details.initiator, "\n");
    },
    { urls: ["<all_urls>"] }
);
chrome.action.onClicked.addListener((tab) => {
    console.log("action button has been clicked\n")
    chrome.debugger.attach({ tabId: tab.id }, '1.0', () => {
        // Send the Network.enable command to enable network tracking
        chrome.debugger.sendCommand({ tabId: tab.id }, 'Network.enable', {}, () => {
            // Add an event listener for the Network.requestWillBeSent event
            chrome.debugger.onEvent.addListener((source, method, params) => {
                if (source.tabId === tab.id && method === 'Network.responseReceived') {
                    // Add the request to the list of sub-resource fetches
                    if (params.response.mimeType === 'application/json' && params.response.url.includes("url")) {
                        console.log(params.response, "\n")
                        console.log(params.response.url)
                    }
                }
            });
        });
    });
})

是的,与webRequest版本不同,我在Chrome.debugger中将搜索范围缩小到了json响应,这实际上是我想要的,但调试警告对用户来说并不好。所以我的烦恼在这里;
1.有没有一种方法,仍然使用Chrome.debugger的工作解决方案来摆脱警告,因为这本质上是这种方法的问题。我不认为用户会喜欢这样,对吧?
2a)我更喜欢Chrome.webRequest方法,非常干净,但是我如何让它像我在网络标签上看到的那样给予我所有的fetch/xhr?
2b)我确实注意到它给我取了一个URL。这实际上是一个js脚本,它是我想要的url的发起者,我如何进入脚本以获得特定的url。我在js脚本的“请求发起者链”中看到了它。

ni65a41a

ni65a41a1#

onBeforeRequest应该能够做你需要的事情。但是,您需要确保您的扩展具有所有必要的权限。这包括访问API的“webRequest”权限,以及允许您拦截特定URL的主机权限。
例如,如果您需要拦截所有网站上的请求,那么您的清单文件可能包含如下属性:

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

如果可能的话,您应该将host_permissions的范围缩小到您实际需要的那些站点。但是,对于子资源,需要注意的是,您需要对请求的URL * 和发起请求的URL * 具有权限。
更多文档可在此处获取:

相关问题