0

如何使用 chrome 扩展在 iframe 或页面中打开当前网站的控制台日志,我为此使用 chrome 调试器协议,但我能够计算日志

chrome.tabs.query({ currentWindow: true, active: true }, function (tabs) {
  console.log("tabs--->", tabs);
  console.log("tabs[0].id", tabs[0].id);

  chrome.debugger.attach({ tabId: tabs[0].id }, "1.1", () => {
    if (chrome.runtime.lastError) {
      console.log("runtime.lastError", chrome.runtime.lastError.message);
      return;
    }
    console.log("Debugger attached");
  });

  chrome.debugger.sendCommand({ tabId: tabs[0].id }, "Console.enable", () => {
    if (chrome.runtime.lastError) {
      console.log("runtime.lastError", chrome.runtime.lastError.message);
      return;
    }
    console.log("Log enabled and result");
  });

  const config = {
    source: "javascript",
    level: "log",
    text: "console.log('hello world')",
  };

  chrome.debugger.sendCommand({ tabId: tabs[0].id }, "Console.ConsoleMessage", config, () => {
    if (chrome.runtime.lastError) {
      console.log("runtime.lastError", chrome.runtime.lastError.message);
      return;
    }
    console.log("Log enabled and result");
  });
});

我已经尝试了上面的代码,它抛出了一个Console.ConsoleMessage未找到的错误

4

1 回答 1

0

获取所有日志

chrome.debugger.getTargets((result) => console.log(result) ) 

这里我们添加了一个事件监听器

chrome.debugger.onEvent.addListener(onEvent);

chrome.tabs.query 为您提供当前选项卡要启用日志,我们必须发送 Log.enable 的命令

chrome.tabs.query({ currentWindow: true, active: true }, function (tabs) {
  // you can even attach tabId or targetId 
  chrome.debugger.attach(
    { targetId: "FC33D8084B688E98F5929B90326E3A27" },
    "1.3",
    () => {
      if (chrome.runtime.lastError) {
        console.log("runtime.lastError", chrome.runtime.lastError.message);
        return;
      }
      console.log("Debugger attached");
    }
  );
  chrome.debugger.sendCommand(
    { targetId: "FC33D8084B688E98F5929B90326E3A27" },
    "Log.enable",
    () => {
      if (chrome.runtime.lastError) {
        console.log("runtime.lastError", chrome.runtime.lastError.message);
        return;
      }
      console.log("Log enabled and result");
    }
  );
});

function onEvent(debuggeeId, message, params) {
 // Here you can get the logs
  console.log("params", params);
}
于 2021-09-23T16:34:59.057 回答