So, I am building a Chrome extension using manifest v3. My content.js is not even being loaded; it’s in the root directory, and when I run ‘npm run build,’ there are no errors
Has anyone here experienced this same error?
I am using ReactJS, Vite, and JavaScript to build this extension.
I am not an experienced dev and here is the code:
content.js
console.log("content.js loaded!");
let fetchDefinition = async (word) => {
try {
let response = await fetch(`https://api.dictionaryapi.dev/api/v2/entries/en/${word}`)
let data = await response.json()
console.log(data);
return data
}
catch(e) {
console.error(e);
}
}
chrome.runtime.onMessage.addListener(async (message, sender, sendResponse) => {
console.log(request, sender, sendResponse);
if (message.action === "findMeaning") {
const selectedText = message.text.trim().toLowerCase();
if (selectedText) {
// Showing a temporary loading bubble
showDefinitionPopup(`Looking up: "${selectedText}"`);
let data = await fetchDefinition(selectedText)
setTimeout(() => {
showDefinitionPopup(`Definition of "${selectedText}":n mock def here`);
}, 1000);
}
}
});
function showDefinitionPopup(content) {
removeExistingPopup();
const popup = document.createElement("div");
popup.id = "wmd-popup";
popup.innerText = content;
Object.assign(popup.style, {
position: "fixed",
top: "20px",
right: "20px",
background: "#fff",
color: "#000",
padding: "12px",
border: "1px solid #ccc",
borderRadius: "8px",
boxShadow: "0 2px 8px rgba(0,0,0,0.2)",
zIndex: "999999",
maxWidth: "300px",
fontSize: "14px",
whiteSpace: "pre-wrap"
});
document.body.appendChild(popup);
setTimeout(() => {
popup.remove();
}, 6000);
}
function removeExistingPopup() {
const existing = document.getElementById("wmd-popup");
if (existing) existing.remove();
}
background.js
chrome.runtime.onInstalled.addListener(() => {
chrome.contextMenus.create({
id: "lookupMeaning",
title: "Find Meaning",
contexts: ["selection"],
});
});
chrome.contextMenus.onClicked.addListener((info, tab) => {
console.log("Context menu clicked!", info, tab);
if (info.menuItemId === "lookupMeaning") {
// Inject content script first
chrome.scripting.executeScript({
target: { tabId: tab.id },
files: ["content.js"]
}, () => {
// Then sending message
chrome.tabs.sendMessage(tab.id, {
action: "findMeaning",
text: info.selectionText
});
});
}
});
manifest.config.js
export default {
name: "Word Meaning Detective",
version: "1.0.0",
manifest_version: 3,
description: "Right-click or select any word to see its meaning instantly.",
permissions: ["contextMenus", "scripting", "tabs", "activeTab"],
host_permissions: ["<all_urls>"],
background: {
service_worker: "background.js"
},
action: {
default_popup: "popup.html",
default_icon: "icon.png"
},
content_scripts: [
{
matches: ["<all_urls>"],
js: ["content.js"]
}
],
icons: {
"16": "icon.png",
"48": "icon.png",
"128": "icon.png"
}
};