_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.
| document.querySelector('h1') |
| <html> | |
| <head>...</head> | |
| <body> | |
| <header> | |
| <h1>🐥 Easy GitHub</h1> | |
| </header> | |
| <script src="popup.js"></script> | |
| </body> | |
| </html> |
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.
| <h1>🐥 Easy GitHub</h1> |
What's returned
🤔 Workaround?
So what you need to do is to request Chrome to execute a document query command on your behalf.
| chrome.tabs.query( | |
| { active: true, windowId: chrome.windows.WINDOW_ID_CURRENT }, | |
| function(tabs) { | |
| const { id: tabId } = tabs[0].url; | |
| let code = `document.querySelector('h1')`; | |
| // http://infoheap.com/chrome-extension-tutorial-access-dom/ | |
| chrome.tabs.executeScript(tabId, { code }, function (result) { | |
| // result has the return value from `code` | |
| }); | |
| } | |
| ); |
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.
| const code = `(function getUrls(){ | |
| const forkUrl = document.querySelector('meta[name="octolytics-dimension-repository_parent_nwo"]') | |
| ? document.querySelector('meta[name="octolytics-dimension-repository_parent_nwo"]').content | |
| : undefined; | |
| const url = document.querySelector('meta[name="go-import"]') | |
| ? document.querySelector('meta[name="go-import"]').content.split(' ')[0] | |
| : undefined; | |
| return { forkUrl, url }; | |
| })()`; |
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.