Im trying to make a chrome extension that lets you add a highlighted piece of text into the DOM of the extension using the context menu. This piece of code works fine but only when I have the devtools from inspecting the extension open. Otherwise the context menu command does nothing. Any help would be appreciated thanks.
Javascript Code:
if (typeof (document) !== "undefined"){
let wordList = []
const ulEl = document.getElementById("ul-el")
const CONTEXT_MENU_ID = "MY_CONTEXT_MENU"
const localStorageStuff = JSON.parse(localStorage.getItem("text"))
if (localStorageStuff){
wordList = localStorageStuff
console.log(wordList)
render(wordList)
}
function render(words) {
let renderWords = ""
for (let i=0; i<words.length; i++) {
renderWords += `
<li>
<a target='blank_' href='http://www.google.com/search?q=${words[i]}'>
${words[i]}
</a>
</li>
`
}
ulEl.innerHTML = renderWords
}
function getword(info) {
if (info.menuItemId !== CONTEXT_MENU_ID) {
return;
}
console.log("Word " + info.selectionText + " was clicked.")
wordList.push(info.selectionText)
console.log(wordList)
localStorage.setItem("text", JSON.stringify(wordList))
render(wordList)
}
chrome.contextMenus.removeAll(function() {chrome.contextMenus.create({
title: "Add log: %s",
contexts:["selection"],
id: CONTEXT_MENU_ID
})})
chrome.contextMenus.onClicked.addListener(getword)
}
manifest.json
{
"name": "Memos",
"version": "1.0",
"manifest_version": 3,
"action": {
"default_popup": "index.html"
},
"permissions": [
"contextMenus",
"tabs",
"storage"
],
"background": {
"service_worker": "index.js"
}
}