Reputation: 5844
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. 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?
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
:
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. However, if I head to the extension's devtools page and inspect that, I can see the "Result:" log there and it reads:
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. Apparently it executes in the context of the page and not the context of its DevTools.
How can I programmatically set the inspected element in DevTools from my extension?
Upvotes: 1
Views: 1893
Reputation: 5844
As @Pa Wa pointed me to, chrome.devtools.inspectedWindow
did the job via its eval()
method:
chrome.devtools.inspectedWindow.eval('inspect(document.body)');
It doesn't even require a debugger attached.
Upvotes: 1