"chrome extension: is there a ways to access the $0 (the selected console element) from an extension?" Code Answer


$0 is only meaningful when the developer tools are still activated. the only way to get the result of $0 is through a devtools page.

a devtools page can communicate with the rest of your extension using the message passing apis. under normal circumstances, the state of the dev tools (open/closed) is known and fixed for the lifetime of the (page action) popup the devtools cannot be toggled while the popup is open unless the popup is being inspected.
so, the devtools page should be a receiver chrome.runtime.onmessage or chrome.runtime.onconnect, and the popup should be a sender chrome.riuntime.sendmessage or chrome.runtime.connect.

within the dev tools page, you can easily interact with the last inspected element using chrome.devtools.inspectedwindow.eval:

// e.g. test if the currently inspected element is the main <body> element
chrome.devtools.inspectedwindow.eval('$0 === document.body', function(result) {
    alert('$0 is ' + (result ? '' : 'not ') + '<body>');

the result of the last expression is passed back to the callback. this value must be serializable, so you cannot "return" the dom element itself. consequently, you cannot get direct access to the dom element, any interaction with the inspected element has to be done through the devtools api.

By Elangovan on September 1 2022

Answers related to “chrome extension: is there a ways to access the $0 (the selected console element) from an extension?”

Only authorized users can answer the Search term. Please sign in first, or register a free account.