首页 > 解决方案 > 将 .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 并替换它,但保留tab[0].url活动页面中的 url 以将其嵌入为 iframe

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

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

标签: google-chromegoogle-chrome-extensionbrowser-extensiondocument.writechrome-extension-manifest-v3

解决方案


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

}


推荐阅读