从background.js传递值到弹出窗口 [英] passing a value from background.js to popup
问题描述
在background.js中,我像这样创建一个弹出窗口:
In background.js, I create a popup like so:
chrome.windows.create({
focused: true,
width: 1170,
url : "settings/index.html",
type: "popup"
}, function(popup) {
tab_app = popup.id;
alert(tab_app);
});
我将ID存储在tab_app中.
I store the id in tab_app.
如何将background.js中的值传递给弹出窗口?
how can I pass a value from background.js to my popup?
我正在这样尝试:
chrome.tabs.executeScript(tab_app, {code: "alert("+message.add+");"});
,但它一直告诉我该选项卡ID不存在.. im假定它是因为其弹出窗口.将不胜感激.
but it keeps telling me that this tab id doesnt exist.. im assuming its because its a popup. will appreciate some help.
推荐答案
Since it's your extension page, the method of choice is Messaging.
注意:您不能使用chrome.tabs.sendMessage
的按标签的消息传递,因为这明确地针对内容脚本上下文(扩展页面不存在).您需要使用将发送到所有其他扩展页面的广播" chrome.runtime.sendMessage
.
Note: you can't use the per-tab messaging of chrome.tabs.sendMessage
, since this explicitly targets the content script context (that doesn't exist for extension pages). You need to use the "broadcast" chrome.runtime.sendMessage
that will send to all other extension pages.
如果一次可以有多个弹出式窗口,则可能是一个问题-您需要使用一些标识符.您可以将其作为网址参数或网址哈希值传递,例如"settings/index.html?id=foo"
或"settings/index.html#foo"
.如果您不希望出现一个以上的弹出式窗口(您可以始终在打开一个新窗口之前检查一个窗口是否打开),那就没关系了.
If you can have more than one popup-type window at a time, this may be a problem - you need some identifier to go along. You could pass it as a URL parameter or a URL hash, e.g. "settings/index.html?id=foo"
or "settings/index.html#foo"
. If you don't expect more than one popup-type window (you can always check if one is open before opening a new one), it doesn't matter.
如果您真的需要动态代码加载或执行,而不仅仅是传递数据(可疑),则需要注意
If you really need dynamic code loading or execution, not just passing data (doubtful), you need to be mindful of CSP.
- 您只需创建一个
<script>
标记并将其添加到文档中,就可以从扩展程序包中动态加载脚本. - 但是,默认情况下,您不能在扩展上下文中传递代码字符串和
eval
.您可以 在CSP字符串中添加'unsafe-eval'
,但这通常是个坏主意. - 很可能,您只需要将某些命令与数据一起传递即可.纯粹的消息传递非常有用,只需查看文档即可.
- You can dynamically load a script from your extension's package by just creating and adding a
<script>
tag to the document. - However, you can't, by default, pass a string of code and
eval
it in the extension context. You could add'unsafe-eval'
to CSP string, but that's a bad idea in general. - Most probably, you only need some commands to be passed along with data. Pure messaging is great for it, just look at the docs.
此我的旧答案可能有用-我正在使用打开新标签并将数据传递到打印出来.
This old answer of mine may be of use - I'm using opening a new tab and passing data there to print it.
这篇关于从background.js传递值到弹出窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!