I am creating my first chrome extension, i need to render the extension HTML once the extension is loaded depending on some data that i pre-created manually, no fetch from any external server, i have created all necessary assets of the extension and now i need to use popup.js
to create the extension markup
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}>`
})
})
}
and in background.js
let books = [
//books objects
]
chrome.runtime.onInstalled.addListener(() => {
chrome.storage.sync.set({ books});
});
Unfortunately, this doesn't work, i get nothing rendered in the extension, it is the my first extension so may be i am missing something and i need to know what i am doing wrong here?
CodePudding user response:
chrome.scripting.executeScript runs the script in the active web page in the tab, but the popup is a separate page with a chrome-extension:// URL shown in a separate window, completely unrelated to the web page. The popup.js script you load in your popup.html runs in that window so you should simply access its window
, document
, and DOM directly.
There's also no need for the background script and storage, just put the data in popup.js:
const books = [
{name: 'foo'},
{name: 'bar'},
];
document.getElementById('book-list').innerHTML =
books.map(b => `<input placeholder=${b.name}>`).join('');
There's no need to wait for load
either, just put your script at the end of body in popup.html:
<body>
<div id="book-list"></div>
<script src=popup.js></script>
</body>