Skip to content

Instantly share code, notes, and snippets.

@devjin0617
Created May 19, 2017 15:15
Show Gist options
  • Save devjin0617/3e8d72d94c1b9e69690717a219644c7a to your computer and use it in GitHub Desktop.
Save devjin0617/3e8d72d94c1b9e69690717a219644c7a to your computer and use it in GitHub Desktop.
chrome extension using a content script to access the `window` object
{
"content_scripts": [
{
"matches": ["http://*/*", "https://*/*"],
"js": ["inject.js"],
"all_frames": true
}
],
"web_accessible_resources": [
"content.js"
]
}
console.log(window);
/**
* injectScript - Inject internal script to available access to the `window`
*
* @param {type} file_path Local path of the internal script.
* @param {type} tag The tag as string, where the script will be append (default: 'body').
* @see {@link http://stackoverflow.com/questions/20499994/access-window-variable-from-content-script}
*/
function injectScript(file_path, tag) {
var node = document.getElementsByTagName(tag)[0];
var script = document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', file_path);
node.appendChild(script);
}
injectScript(chrome.extension.getURL('content.js'), 'body');
@js-4
Copy link

js-4 commented Sep 26, 2023

@thecrazybob Thank you so much. I have spent hours trying to get to the (same) global window object. This comment is underrated and should be quicker to find. Have a nice day!

@milkmanjr
Copy link

@thecrazybob you saved the day! Cheers 🥂

@guest271314
Copy link

Unfortunately content scripts don't work for isolated-app: protocol.

@houtianze
Copy link

Thanks for the info share here. Found out executeScript also does the trick.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment