Getting DOM content from Chrome Extension


_Photo by James Barnett on _Unsplash

When you trying to get a DOM content in Chrome tab from an extension using document.getElementBy* or document.querySelector*, you get the DOM content of your extension HTML.

Suppose that you have a following default popup (specified as page_action -> default_popup in manifest.json).
And select the h1 content in popup.js referenced in page_option.html.



Then instead of getting the current DOM content displayed in the Chrome tab, it returns the DOM of the page_option.html instead.


What's returned

🤔 Workaround?

So what you need to do is to request Chrome to execute a document query command on your behalf.



First you get the currently active Tab's ID (tabId).

Refer to Chrome extension tutorial – access active page dom on how that works.

Then you execute a code on the current tab (line #9). and the callback gives you result which is the result of document.querySelector.

If you want need to execute multiple queries, just put them in an IIFE.


Using IIFE to run multiple queries

Parting Words

I've learned about it recently while writing a Chrome extension, Easy GitHub (work-in-progress).

You can see the relevant code snippets here on GitHub.