我正在构建一个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替换新窗口而不是渲染文本?
发布于 2021-05-19 22:08:55
使用.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);
}
}https://stackoverflow.com/questions/67509376
复制相似问题