我正在創建我的第一個 chrome 擴展,一旦加載擴展,我需要渲染擴展 HTML,這取決于我手動預先創建的一些資料,沒有從任何外部服務器獲取,我已經創建了擴展的所有必要資產,現在我需要用于popup.js創建擴展標記
popup.js
const body = document.getElementById('body') // extenstion HTML body
const bookList = document.getElementById('book-list')
body.addEventListener('load', async () => {
let [tab] = await chrome.tabs.query({ active:true,currentWindow:true})
chrome.scripting.executeScript({
target: { tabId: tab.id },
function: renderExtension,
});
});
function renderExtension() {
chrome.storage.sync.get("books", ({ books}) => {
books.forEach(book=> {
bookList.innerHTML = `<input placeholder=${book.name}>`
})
})
}
并且在background.js
let books = [
//books objects
]
chrome.runtime.onInstalled.addListener(() => {
chrome.storage.sync.set({ books});
});
不幸的是,這不起作用,我在擴展中沒有得到任何渲染,這是我的第一個擴展,所以可能是我遺漏了一些東西,我需要知道我在這里做錯了什么?
uj5u.com熱心網友回復:
chrome.scripting.executeScript 在選項卡的活動網頁中運行腳本,但彈出視窗是一個單獨的頁面,其 chrome-extension:// URL 顯示在一個單獨的視窗中,與網頁完全無關。您在 popup.html 中加載的 popup.js 腳本在該視窗中運行,因此您應該直接訪問它的window、document和 DOM。
也不需要后臺腳本和存盤,只需將資料放在popup.js中:
const books = [
{name: 'foo'},
{name: 'bar'},
];
document.getElementById('book-list').innerHTML =
books.map(b => `<input placeholder=${b.name}>`).join('');
也無需等待load,只需將腳本放在popup.html的正文末尾即可:
<body>
<div id="book-list"></div>
<script src=popup.js></script>
</body>
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/442107.html
上一篇:如何使用discord.jsv13中的檔案對命令進行分類
下一篇:根據陣列中的值過濾物件
