Вставить .html файл из упакованного каталога расширений Chrome в новую вкладку окна
Я создаю расширение Chrome (v3), и я пытаюсь загрузить его из каталога расширения и заменить старый 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 я сначала создал новое окно. Затем я попытался внедрить сценарий содержимого, который перезаписывает текущий html моим
index.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, а не отображать текст?
1 ответ
Один из способов чтения содержимого локального
.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);
}
}