2019-02-10

Getting DOM content from Chrome Extension

programming, selfnote, chromeplugin

banner

_Photo by Sai Kiran Anagani on _Unsplash

Note to self on how to get DOM content from Chrome Extension

As I was building a Chrome Extension, Easy GitHub to generate I had to get DOM content on a GitHub page to see if it's a forked page or not.

Easy GitHub is to display initially a way to sync forked repository with the master repository.

Reference Paul Seal's blog - How to keep your fork up to date with the master repository in GitHub

For forked GitHub page, GitHub page contains a meta tag named octolytics-dimension-repository_parent_nwo , which contains the parent repository the current repository is forked from.

But if the current page is not a fork repo page, then it doesn't have octolytics-dimension-repository_parent_nwo but have to use go-import meta value.

As a last resort, I needed to use window.location.href(or show a message that it's not a repo page in Chrome Extension popup).

When using document.getElementBy* or document.querySelector* within Chrome Extension, it fetches DOM for the extension HTML files, not from the tab content.

So to retrieve DOM content, one need to execute a script within a tab by sending a query (document.querySelector* or document.getElement*) like following.

https://gist.github.com/dance2die/7c79a1e09b334da6d723bd07e2bb7682

Execute Script within a Tab to extract DOM content

Source code on GitHub.

You can see above that, you pass a code to query DOM elements and extract URLs, which you can use to create a git command script.

You can add a tabs permission to execute the script but it can be too detrimental thus you can simply add URLs to allow script executions.

https://gist.github.com/dance2die/ff058d7fbc01103b1c3e8df4caae74dc

"permissions" section in Chrome Extension manifest.json

Reference - Stack Overflow - chrome.tabs.executeScript not working?