How to retrieve the Initiator of a request when extending Chrome DevTool?

可紊 提交于 2019-12-01 00:21:27

问题


I am writing an extension which needs to know who is responsible when a network request is made. The Initiator from the Network Panel is exactly what I want. But I am not able get it using devtools.network or devtools.panels API. Is it because they simply do not expose that information or I am missing something?


回答1:


You are correct in that the initiator is not exposed through devtools extensions API -- currently, the resource properties that the API exposes are limited to that in HAR specification, which does not include initiator. You can use raw DevTools protocol (https://developers.google.com/chrome-developer-tools/docs/debugger-protocol) to get all data available to the DevTools front-end. Note that it is exposed to Chrome extensions as well (http://developer.chrome.com/extensions/debugger.html), but you can't use it when the DevTools front-end is opened, so you won't be able to access it in a DevTools extension.

Depending on what you're trying to do, experimental Timeline API may be of some use (this test shows how this is done: https://code.google.com/p/chromium/codesearch#chromium/src/third_party/WebKit/LayoutTests/inspector/extensions/extensions-events.html&q=webInspector.timeline&sq=package:chromium&type=cs&l=148). Unlike initiators in Network, it won't show you the location in the document that cause a statically referred resource to get loaded, but it will give you stack traces for XHRs and resources that get dynamically added to the document.




回答2:


This may have changed since the original answer but for future reference this is possible through the debugger extension API listening to network events

Example (within an extension)

var tabId = parseInt(window.location.search.substring(1));

window.addEventListener("load", function() {
  chrome.debugger.sendCommand({tabId:tabId}, "Network.enable");
  chrome.debugger.onEvent.addListener(onEvent);
});

window.addEventListener("unload", function() {
  chrome.debugger.detach({tabId:tabId});
});

var requests = {};

function onEvent(debuggeeId, message, params) {
  if (tabId != debuggeeId.tabId)
    return;

  if (message == "Network.requestWillBeSent") {
    console.log(params.initiator);
  }
}

The code was modified from the HTTP extension example



来源:https://stackoverflow.com/questions/17650466/how-to-retrieve-the-initiator-of-a-request-when-extending-chrome-devtool

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!