【发布时间】:2020-04-12 11:12:14
【问题描述】:
我开发了一个 Chrome 扩展程序,它主要与 firefox 网络扩展 API 兼容。只有一个问题:
在 Chrome 扩展中,我有 popup.js 和 background.js。用户单击一个按钮,popup.js 将 chrome.sendMessage 发送到接收数据的 background.js,然后(popup.html 可能同时关闭)我只是在 background.js 中调用:
newWin = window.open("about:blank", "Document Query", "width=800,height=500");
newWin.document.open();
newWin.document.write('<html><body><pre>' + documentJson + '</pre></body></html>');
// newWin.document.close();
这样在 Chrome 扩展程序中可以正常工作,但在 Firefox 中不行。我在这里(https://javascript.info/popup-windows)读到,出于安全原因,Firefox 只会通过“按钮单击事件”打开。如果我将上面的代码移动到 popup.js,在 button-click-evenListener 内,它将以这种方式打开(但我还没有准备好数据,这真的不是我想要的)
所以我尝试了我找到的所有东西,但我没有让 chrome.tabs.executeScript 运行。这是我的 cmets 代码:
popup.js
// working in firefox and chrome (popup.js)
const newWin = window.open("about:blank", "hello", "width=200,height=200");
newWin.document.write("Hello, world!");
// not working firefox: id's match, he enters function (newWindow) but document.write doing nothing (but no error in log)
// not working chrome: doesnt even enter "function (newWindow)""
chrome.windows.create({
type: 'popup',
url: "output.html"
}, function (newWindow) {
console.log(newWindow);
console.log(newWindow.id);
chrome.tabs.executeScript(newWindow.tabs[0].id, {
code: 'document.write("hello world");'
});
});
background.js
(创建本地 output.html 并在 Manifest.json 中授予多个权限 - tabs、activeTab、output.html、、about:blank)
// opening but executeScript not working in firefox: Unchecked lastError value: Error: The operation is insecure.
// opening but executeScript not working in chrome: Unchecked runtime.lastError: Cannot access contents of url "chrome-extension://plhphckppghaijagdmghdnjpilpdidkh/output.html". Extension manifest must request permission to access this host
chrome.tabs.create({
// type: 'popup',
url: "output.html"
}, function (newWindow) {
console.log(newWindow);
console.log(newWindow.id);
chrome.tabs.executeScript(newWindow.id, {
code: 'document.write("hello world");'
});
});
如何从 background.js 将数据输入新窗口/弹出窗口 - 我可以从那里打开一个空页面,所以它只是让 executeScript() 运行
【问题讨论】:
-
现代方法是将数据传递到专用页面example。
-
顺便说一句,executeScript 对您没有帮助,因为它仅适用于内容脚本,并且适用于网页,而不适用于扩展页面。
-
感谢您的回答!我查看了“现代方法”,我需要解决方案 4。(背景页面)。仍然希望有一些简单的解决方案,因为我现在有一个 3-liner 做这项工作。还要感谢 executeScript 的解释,API 文档并没有那么精确地说明它仅适用于内容脚本 - 但现在我看到了他们给出的“提示”,这解释了为什么我无法让它工作
-
您可以使用包含完整 html 的数据 URI 而不是 about:blank。
-
真棒@wOxxOm !这正是我所希望的简单解决方案——我从没想过 :) 我将发布我的问题的答案。如果你愿意,我想给你一点赏金,请查看 dashdevs.org 并加入 discord,我在那里(这里没有办法 PM)
标签: javascript browser google-chrome-extension tabs firefox-addon