Skip to content

Instantly share code, notes, and snippets.

@devjin0617
Created May 19, 2017 15:15
Show Gist options
  • Select an option

  • Save devjin0617/3e8d72d94c1b9e69690717a219644c7a to your computer and use it in GitHub Desktop.

Select an option

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');
@bennadel

Copy link
Copy Markdown

Thank you! This was exactly what I needed.

@johnny1K

johnny1K commented Feb 9, 2021

Copy link
Copy Markdown

Thanks!

@RabiRoshan

Copy link
Copy Markdown

Just what I was looking for.... Thanks a lot mate!

@gagregrog

Copy link
Copy Markdown

This is great, thanks!

It's worth pointing out that the manifest_version should be 2 for this to work properly. Things work a little differently in version 3.

@tsikerdekis

Copy link
Copy Markdown

Does anyone have the solution for version 3?

@dpw1

dpw1 commented May 9, 2021

Copy link
Copy Markdown

Does anyone have the solution for version 3?

I'm also looking for a way to achieve on version 3.

@tunjayhuseynov

Copy link
Copy Markdown

For Manifest V3:

Changes in Manifest:

 "web_accessible_resources": [
   {
     "resources": ["content.js"],
     "matches": ["https://*.anywebsite.com/*"]
   }
 ]

Changes in Inject.js

injectScript(chrome.runtime.getURL('content.js'), 'body');

Others stay the same

@sankarkumar23

Copy link
Copy Markdown

How can I return one of the window variable (a complex JSON object) to content script. I am using v3.

@Dylan0916

Copy link
Copy Markdown

How can I return one of the window variable (a complex JSON object) to content script. I am using v3.

+1, I also wanna know

@silverbirder

Copy link
Copy Markdown

Use window.postMessage and window.addEventListener

@PixelMelt

Copy link
Copy Markdown

Use window.postMessage and window.addEventListener

could you elaborate?

@silverbirder

Copy link
Copy Markdown

manifest.json

  "content_scripts": [
    {
      "js": [
        "content-script.js"
      ]
    }
  ],
  "web_accessible_resources": [
    {
      "resources": [
        "web_accessible_resources.js"
      ]
    }
  ],

web_accessible_resources.js

window.postMessage({ from: 'web_accessible_resources.js', data: window["hoge"] })

content-script.js

const handleFromWeb = async (event) => {
    if (event.data.from) {
        const data = event.data.data;
        console.log(`process from ${event.data.from}`);
        console.log(data);
    }
};
window.addEventListener('message', handleFromWeb);

※ Refer to my repo

@vinciest

Copy link
Copy Markdown

Nice!

@DanKeane

Copy link
Copy Markdown

If anyone is still looking.

Manifest.js

"content_scripts": [
        {
            "matches": ["<all_urls>"],
            "js": ["js/inject.js"]
        }
],
"web_accessible_resources": [{ 
        "resources": ["js/*"],
        "matches": ["<all_urls>"]

}],

using "js/*" for all files inside the js directory.

inject.js

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);
    console.log("injected")
}

injectScript(chrome.runtime.getURL('!READBELOW!'), 'body');

When using injectingScript, pass file dir (if you have one) / file name
example: js/main.js

@lyan-ap

lyan-ap commented Nov 18, 2022

Copy link
Copy Markdown

can't read data still

@thecrazybob

Copy link
Copy Markdown

The world can be set to MAIN so the script shares the same ExecutionWorld. Example:

"content_scripts": [
        {
            "matches": ["https://*.domain.com/*"],
            "js": ["content.js"],
            "world": "MAIN"
        }
 ]

@wilsonsilva

Copy link
Copy Markdown

Thanks, @thecrazybob. You posted this just in time!

@kiki67100

kiki67100 commented Jun 8, 2023

Copy link
Copy Markdown

Too bad I didn't see it before! I wanted to retrieve a token from the window an authorization token bearer object.

I used chrome.webRequest.onBeforeSendHeaders.addListener(handler, requestFilter, extraInfoSpec); to intercept the token and send it with sendMessage from background.js and content.js it works perfectly and it's transparent ;)

From background.js

chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {

    if(message==="give_me_headers"){
        sendResponse(global_header_for_fetch);
    });
[...]

let global_header_for_fetch=[]; // global 

header_for_fetch = {};
            for (i = 0; i < requestHeaders.length; i++) {
                header_for_fetch[requestHeaders[i].name] = requestHeaders[i].value;
            }

            global_header_for_fetch=header_for_fetch;

[...]

from content.js


chrome.runtime.sendMessage('give_me_headers',function(response){
               headers_for_fetch=new Headers(response);
});


@austin2035

Copy link
Copy Markdown

If anyone is still looking. It's work well.

mainfest.json v3

 "content_scripts": [
    {
      "matches": ["https://www.youtube.com/watch*"],
      "js": ["js/vendor.js", "js/content_script.js"],
      "run_at": "document_end",
      "all_frames": true
    }
  ],
  "web_accessible_resources": [
    {
      "resources": ["js/vendor.js", "js/web_accessible_resources.js"],
      "matches": ["<all_urls>"]
    }
  ],

content_script.js

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.runtime.getURL('js/web_accessible_resources.js'), 'body');

var port = chrome.runtime.connect();

window.addEventListener("message", (event) => {
  // We only accept messages from ourselves
  if (event.source !== window) {
    return;
  }

  if (event.data.type && (event.data.type === "FROM_PAGE")) {
    console.log("Content script received: " + event.data.text);
    port.postMessage(event.data.text);
  }
}, false);

web_accessible_resources.js

console.log(window.xxx)
window.postMessage({type : "FROM_PAGE", text : JSON.stringify(window.xxx)}, "*");

I hope this will help you. Good luck!

@js-4

js-4 commented Sep 26, 2023

Copy link
Copy Markdown

@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
Copy Markdown

@thecrazybob you saved the day! Cheers 🥂

@guest271314

Copy link
Copy Markdown

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

@houtianze

Copy link
Copy Markdown

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