首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >将.html文件从打包的铬扩展目录注入新的窗口选项卡

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

Stack Overflow用户
提问于 2021-05-12 18:44:24
回答 1查看 706关注 0票数 0

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

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

代码语言:javascript
运行
复制
let template = chrome.runtime.getURL("assets/index.html");

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

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

代码语言:javascript
运行
复制
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嵌入。

代码语言:javascript
运行
复制
function setBackground(){
  chrome.storage.sync.get("data", ({ data }) => {
      document.write(data.template);
      //add tab[0].url as iframe
  });
}

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

EN

回答 1

Stack Overflow用户

发布于 2021-05-19 22:08:55

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

代码语言:javascript
运行
复制
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);
      }

}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67509376

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档