将 .html 文件从打包的 chrome 扩展目录注入新窗口选项卡

问题描述

我正在构建一个 Chrome 扩展程序 (v3),我试图从扩展程序的目录中加载一个 index.html,并在新创建的窗口中用我的 html 替换旧的 html。但它不是 html,而是呈现为文本。这是我目前得到的:

我将 html 文件存储在我的 background.js 中:

let template = chrome.runtime.getURL("assets/index.html");

chrome.runtime.onInstalled.addListener( () => {
  chrome.storage.sync.set({ "data": {"template" : template } });
});

在我的 popup.js 中,我首先创建了一个新窗口。然后我尝试注入一个内容脚本,用我的 index.html 文件覆盖当前的 html,如下所示:

button.addEventListener("click",async () => {
  //get url of current tab
  let tab = await chrome.tabs.query({ active: true,currentwindow: true });

  //create new window
  let newWindow = await chrome.windows.create({
    url : tab[0].url,type : "popup",width: dims.cssWidth,height: dims.cssHeight,state: "normal"
  })

  const tabId = newWindow.tabs[0].id;
  if (!newWindow.tabs[0].url) await onTabUrlUpdated(tabId);

  const results = await chrome.scripting.executeScript({
      target: {tabId},function: setBackground,});

});

setBackground() 函数删除现有的 html 并替换它,但保留活动页面的 url tab[0].url 以将其嵌入为 iframe

function setBackground(){
  chrome.storage.sync.get("data",({ data }) => {
      document.write(data.template);
      //add tab[0].url as iframe
  });
}

如何用我自己的 html 替换新窗口而不是渲染文本?

解决方法

使用 .html 读取本地 fetch 文件内容的一种方法如下:

function setBackground(){
      try {
        //fetch local asset
        const res = await fetch(chrome.runtime.getURL("/assets/index.html"));
        const myhtml = await res.text()
        document.write(myhtml);

      } catch(err){
          console.log("fetch error",err);
      }

}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...