我正在构建一个 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 替换新窗口而不是渲染文本?
答案 0 :(得分:0)
使用 .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);
}
}