简体   繁体   English

从Chrome扩展程序内调用DevTools的inspect()函数

[英]Invoke the inspect() function of DevTools from within a chrome extension

I want to create an extension that can programmatically inspect an element as if the user right-clicked on an element and clicked "Inspect." 我想创建一个扩展,该扩展可以以编程方式检查元素,就像用户在元素上单击鼠标右键并单击“检查”一样。 I want that to happen, preferably, from a devtools page set via devtools_page in the manifest. 我希望最好通过清单中通过devtools_page设置的devtools页面来实现。 I want the exact behavior - Elements panel opens, the element is highlighted on the left and its styles on the right sidebar. 我想要确切的行为-元素面板打开,该元素在左侧突出显示,其样式在右侧栏。

How would I achieve that? 我将如何实现?

What I've tried 我尝试过的

As a starting point, I want the extension to attach a debugger and inspect the document body once I click on the extension icon on top. 首先,我希望扩展程序在单击顶部的扩展程序图标时附加调试器并检查文档正文。 Here's my devtools_page : 这是我的devtools_page

chrome.browserAction.onClicked.addListener(function (tab) {
    chrome.debugger.attach({tabId: tab.id}, "1.0", function () {
        chrome.debugger.sendCommand({tabId: tab.id}, 'Runtime.evaluate', {
            expression: 'console.log(document.body); inspect(document.body);'
        }, function () {
            console.log('Result:', arguments);
        }); 
    });
});

If I now look at the DevTools window of the page I'm inspecting, I can correctly see the log of the body and click on it to open the element inside the inspector. 现在,如果我查看正在检查的页面的DevTools窗口,则可以正确看到body的日志,然后单击它以在检查器中打开该元素。 However, if I head to the extension's devtools page and inspect that , I can see the "Result:" log there and it reads: 但是,如果我前往扩展的devtools页面和检查我可以看到“结果:”日志那里记载:

Result:
Arguments(1)
  0:
    exceptionDetails: {columnNumber: 28, exception: {…}, exceptionId: 2, lineNumber: 0, scriptId: "88", …}
    result:
      className: "ReferenceError"
      description: "ReferenceError: inspect is not defined↵    at <anonymous>:1:29"
      objectId: "{"injectedScriptId":1,"id":1}"
      subtype: "error"
      type: "object"
      __proto__: Object
    __proto__: Object

So the evaluated code doesn't have access to the inspect() function, even though it has access to the element I want to inspect. 因此,即使评估后的代码可以访问我要检查的元素,也无法访问inspect()函数。 Apparently it executes in the context of the page and not the context of its DevTools. 显然,它在页面的上下文中执行,而不是在其DevTools的上下文中执行。

How can I programmatically set the inspected element in DevTools from my extension? 如何通过扩展程序以编程方式在DevTools中设置被检查元素?

As @Pa Wa pointed me to, chrome.devtools.inspectedWindow did the job via its eval() method: 正如@Pa Wa指出的那样, chrome.devtools.inspectedWindow通过其eval()方法完成了这项工作:

chrome.devtools.inspectedWindow.eval('inspect(document.body)');

It doesn't even require a debugger attached. 它甚至不需要附加调试器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM