首页 > 解决方案 > Firefox 扩展:打开窗口并写入动态内容

问题描述

我开发了一个 Chrome 扩展程序,它主要与 firefox web-extensions 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 运行。这是我的带有注释的代码:

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");'
      });
    });

背景.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() 运行

标签: javascriptbrowsergoogle-chrome-extensiontabsfirefox-addon

解决方案


感谢@wOxxOm 将我指向一个数据URI,以便将json 文档从background.js 传输到浏览器中。

在搜索构建数据 URI 的 javascript 方法时,我发现了这个线程,并建议创建一个Blobhttps ://stackoverflow.com/a/57243399/13292573

所以我的解决方案是这样的:

背景.js

var documentJson = JSON.stringify(documents, null, 2)
let a = URL.createObjectURL(new Blob([documentJson]))
chrome.windows.create({
  type: 'popup',
  url: a
});


推荐阅读