_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.
https://gist.github.com/dance2die/23f4b80ad83768e1ff073293d64d9bdc
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.
https://gist.github.com/dance2die/65173f48ef0893ba6ce0126d7c42444d
What's returned
🤔 Workaround?
So what you need to do is to request Chrome to execute a document query command on your behalf.
https://gist.github.com/dance2die/d05924be83c6be1b20ba94206ff2beb0
popup.js
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.
https://gist.github.com/dance2die/bfbb7085d70fa3b6212a72c0ca8a11e1
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.