google-chrome - 将 .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 替换新窗口而不是渲染文本?
解决方案
.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);
}
}
推荐阅读
- javascript - Reactjs Javascript if/else 无法正常工作
- bash - Bash:根据文件名排序文件
- python - 如何检查时间戳列表的元素是否在包含时间戳的系列中?
- python - 在 Node-RED 中使用 Python 节点而不暴露代码
- javascript - 在shopify中向product-card-grid.liquid写入函数时,Javascript简单函数未执行?
- ruby-on-rails - 如何使用 exec_params where params in ('','','')
- c# - 表单帖子字段之一返回 NULL .NET Core MVC
- java - mybatis中如何将String[]映射到PostgreSQL数组列
- reactjs - SyntaxError: Unexpected token < at ScriptTransformer._transformAndBuildScript (../../node_modules/jest-runtime/build/script_transformer.js
- .net-core - .NET 5 未编译为单个文件可执行文件