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).
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.getElement*) like following.
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.
Reference – Stack Overflow – chrome.tabs.executeScript not working?