2

I have a simple extension that uses a devtools page to provide debugging functionality. When the browserAction icon is clicked, that page inserts a content script in the current tab. How do I pass a DOM node (or nodeId) from the content script back to the devtools page so that inspect() can be called on it?

Here's what I tried

manifest.json contains:

"devtools_page": "devtools.html"

devtools.html contains:

<script src="devtools-script.js"></script>

devtools-script.js:

chrome.browserAction.onClicked.addListener(function(tab) {
    chrome.tabs.executeScript(tab.id, {
        file: 'js/content.js'
    }, function () {
        chrome.devtools.inspectedWindow.eval('window.searchedElement', {
            useContentScriptContext: true
        }, function (result) {
            console.log('resulting element:', result);
        });
    });
});

content.js:

window.searchedElement = document.body;

(I used document.body to simplify the example)


Now, when I navigate to a page, open DevTools and click on the extension, the following happens:

  1. DevTools opens my devtools.html page (when DevTools is opened, before the click)
  2. My devtools page injects my content script (after the click)
  3. Content script code sets the searched element
  4. DevTools page performs eval() to return the element previously set by the content script

The resulting log from the devtools-script is:

resulting element: {}

So apparently you can't pass the node that easily. I can maybe give the element an id attribute in the content script and then query it in the devtools page, but that seems clumsy.

Is there a better way to get access to an element in the inspected window from the devtools page?

dodov
  • 5,206
  • 3
  • 34
  • 65
  • 3
    Only JSON-ifiable data can be transferred between processes (like content script, devtools page, background script page) in a Chrome extension, and DOM elements aren't JSON-ifiable. I think your content script can [get the elements's index](https://stackoverflow.com/a/39395069) in document.getElementsByTagName('*'), then your devtools script should be able to use devtools console API `inspect(document.getElementsByTagName('*')[thatIndex])` – wOxxOm Sep 07 '18 at 07:37

0 Answers0