如何使用 Chrome 调试器从 Chrome 扩展中的 iframe 获取请求

问题描述 投票:0回答:1

我正在编写 Chtome 扩展,它使用 Chrome 调试器并收集状态代码 >= 400 的请求和响应。 我正在使用选项卡 API 来获取活动选项卡并将调试器附加到它

chrome.debugger.attach({ tabId: tabId }, "1.3", () => {...})
稍后在代码中我正在监听事件:


chrome.debugger.onEvent.addListener((source, method, params) => {

    if (method === "Network.requestWillBeSent") {...})

但看起来我只能捕获在活动选项卡上下文中发送的请求,但如果选项卡有 iframe,调试器将不会捕获该事件。

我尝试使用来自 https://developer.chrome.com/docs/extensions/reference/api/debugger#attach_to_lated_targets 在调用之前

chrome.debugger.attach
但可能做错了什么,因为仍然无法捕获 iframe 请求。

我不确定我是否正确附加了子会话,或者问题出在其他方面。如果有任何建议,我将非常感激。

期望在带有附加调试器的选项卡上的 iframe 发送请求时捕获事件。

google-chrome google-chrome-extension google-chrome-devtools
1个回答
0
投票

所以,通过附加所有可能的目标,问题就解决了。唯一的问题是您可能需要知道要附加到的框架的 URL。希望它对某人有用。

// To keep track of attached iframes. Use it later to detach
let iframes = {};
let debuggerAttached = false;

chrome.runtime.onMessage.addListener(function (request) {
    // I'm sending "getHar" message to capturing requests/responses
    if (request.message === "getHar") {

        // Sending active Tab ID along the message 
        tabId = request.tabId;
        if (!debuggerAttached) {
          debuggerAttached = true;
          chrome.debugger.getTargets((targets) => {
            if (targets) {
              for (let target of targets) {
                if (target.url.includes("URL_WHICH_YOU_MIGHT_WANT_TO_TRACK")) {
                  iframes[target.id] = target;
                  chrome.debugger.attach({ targetId: target.id }, "1.3", () => {
                    if (chrome.runtime.lastError) {
                      console.error(chrome.runtime.lastError.message);
                      return;
                    }
                    chrome.debugger.sendCommand({ targetId: target.id }, "Network.enable", {}, () => {});
                  });
                }
              }
            }
          });

            chrome.debugger.attach({ tabId: tabId }, "1.3", () => {
              if (chrome.runtime.lastError) {
                console.error(chrome.runtime.lastError.message);
                return;
              }
              chrome.debugger.sendCommand({ tabId: tabId }, "Network.enable", {}, () => {});
              // My function which I use to collect requests
              captureHAR(tabId);
            });
          } else {
            // My function which I use to detach from targets
            saveAndDetach(tabId);
          }
    }
});
© www.soinside.com 2019 - 2024. All rights reserved.