Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Chrome extension content scripts access window.opener?

In my extension, I'm trying to determine whether a new tab was created as a popup by another tab and if so, which tab.

I thought I would be able to use window.opener from a content script to help figure this out. But it looks like window.opener doesn't work correctly in content scripts.

When I create a tab manually, it's window.opener is null as expected.

When a tab is created as a popup by another tab, its window.opener is undefined. I can infer from this that the tab was created as a popup, but I can't use it to figure out which tab created the new one.

Is this a known issue, and does anybody know of any workarounds?

like image 229
Greg Avatar asked Sep 01 '10 21:09

Greg


1 Answers

I didn't look closely into this problem, but I think I can point you in the right direction. Content script can't access a variable from a parent window because it is sandboxed. A workaround would be to run your code directly on a page, to do this you need to inject your script inside a script tag:

Your content script would look like this:

function injectJs(link) {
        var scr = document.createElement("script");
        scr.type="text/javascript";
        scr.src=link;
        (document.head || document.body || document.documentElement).appendChild(scr);
}

injectJs(chrome.extension.getURL("inject.js"));

Now you can run your code without sandbox restrictions as if it was right on the page:

inject.js:

alert(window.opener);

I assume you would like to now pass this information back to a background page, which is another challenge as you can't use Chrome API. Good news is that content script can access DOM and listen to DOM events, so you can use them to pass information to a content script which would send it to a background page. I am pretty sure you should be able to register a custom DOM event and have your content script listening to it (haven't tried this part myself).

like image 181
serg Avatar answered Oct 12 '22 15:10

serg