My extension is nearly ready to be submitted, but I can’t work out how to re-factor a part of the code that I hacked together in order for it to work as expected.
My extension is a popup that displays YouTube playlists that are saved in local storage, and the user can either click a button on the UI to add the current video to the list or they can right click on a video to add it.
I’m trying to run my content script from the background script so that it loads immediately, otherwise when I send a message from a context menu click I get the error that no receiving end exists. The hack I used was so load the content script within the context menu onClick event listener after a short delay, but no matter where else in the background script I attempt to run tabs.executeScript I always get an error of some sort.
Ideally I don’t want the user to have to open the extension before they have right-click functionality, so what’s the best way to proceed?
This is the entirety of background.js as the bulk is contained in the popup script and the content script:
function onCreated() {
if (browser.runtime.lastError) {
console.log(`Error: ${browser.runtime.lastError}`);
} else {
console.log("Context menu item created successfully");
}
// EXECUTES BUT CAN'T MAKE A CONNECTION
// browser.tabs.executeScript({file: "/content_scripts/content.js"})
}
browser.contextMenus.create({
id: "add",
title: "Add To Playlist",
contexts: ["all"],
documentUrlPatterns: ["*://www.youtube.com/*"]
}, onCreated);
// ERROR: MISSING HOST PERMISSION FOR THE TAB
// browser.tabs.executeScript({file: "/content_scripts/content.js"})
browser.contextMenus.onClicked.addListener((info) => {
// WORKS HERE BUT ONLY WITH TIMEOUT SET
browser.tabs.executeScript({file: "/content_scripts/content.js"})
///////////////////////////////////////
if(info.menuItemId === "add"){
if(info.linkUrl === undefined){
setTimeout(()=>{
browser.tabs.query({active: true, currentWindow: true})
.then(response =>{
browser.tabs.sendMessage(response[0].id, {
command: "add url",
url: info.pageUrl
})
.then(response => console.log(response))
.catch(error => console.log(error))
})
}, 100)
}else{
setTimeout(()=>{
browser.tabs.query({active: true, currentWindow: true})
.then(response =>{
browser.tabs.sendMessage(response[0].id, {
command: "add url",
url: info.linkUrl
})
.then(response => console.log(response))
.catch(error => console.log(error))
})
}, 100)
}
return;
}
})