简体   繁体   English

Chrome扩展内容脚本可以访问window.opener吗?

[英]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. 我以为我可以使用内容脚本中的window.opener来帮助解决这个问题。 But it looks like window.opener doesn't work correctly in content scripts. 但看起来window.opener在内容脚本中无法正常工作。

When I create a tab manually, it's window.opener is null as expected. 当我手动创建选项卡时,它的window.opener按预期为null。

When a tab is created as a popup by another tab, its window.opener is undefined. 当选项卡被另一个选项卡创建为弹出窗口时,其window.opener未定义。 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? 这是一个已知的问题,有没有人知道任何变通方法?

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: 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. 我假设您现在希望将此信息传回背景页面,这是另一项挑战,因为您无法使用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. 好消息是内容脚本可以访问DOM并监听DOM事件,因此您可以使用它们将信息传递给内容脚本,然后将其发送到后台页面。 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). 我很确定你应该能够注册一个自定义DOM事件并让你的内容脚本听它(我自己没有试过这个部分)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM