Chrome扩展内容脚本可以访问window.opener吗? [英] Can Chrome extension content scripts access window.opener?

查看:529
本文介绍了Chrome扩展内容脚本可以访问window.opener吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的扩展中,我试图确定一个新选项卡是否被创建为另一个选项卡的弹出窗口,如果是,哪个选项卡。



我以为我将能够使用内容脚本中的window.opener来帮助解决这个问题。但它看起来像window.opener不能在内容脚本中正常工作。



当我手动创建一个选项卡时,它的window.opener为空。 >

当一个选项卡被另一个选项卡创建为弹出选项时,其window.opener是未定义的。我可以从中推断出这个选项卡是作为一个弹出式菜单创建的,但我无法用它来确定哪个选项卡创建了新选项卡。



这是一个已知的问题,并确实有人知道任何解决方法?

解决方案

我没有仔细研究这个问题,但我认为我可以指出你在正确的方向。内容脚本不能从父窗口访问变量,因为它是沙盒。解决方法是直接在页面上运行您的代码,为此,您需要将脚本注入到脚本标记中:



您的内容脚本如下所示:

 函数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));

现在,您可以在没有沙盒限制的情况下运行代码,就好像它在页面上一样:



inject.js:

  alert(window.opener); 

我假设您现在想将这些信息传回给后台页面,这是另一个挑战您无法使用Chrome API。好消息是,内容脚本可以访问DOM并监听DOM事件,因此您可以使用它们将信息传递给内容脚本,将其发送到后台页面。我很肯定你应该能够注册一个自定义的DOM事件,并让你的内容脚本听它(自己还没有试过这部分)。

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?

解决方案

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).

这篇关于Chrome扩展内容脚本可以访问window.opener吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆