I am currently writing a personal chrome extension where I can translate text by highlighting it, right-clicking and translate it through the context menu.
I got the context menu working without the actual translation functionality. When I started to implement said functionality using the deepl-node API however I got this error:
"Cannot find module 'deepl-node'. Did you mean to set the 'moduleResolution' option to 'nodenext', or to add aliases to the 'paths' option? ts(2792)"
Therefore I changed my module in tsconfig.json from ESNext to NodeNext and also added the moduleResolution statement and set it to NodeNext aswell.
This solved my issue with the API however it removed my menu choice from the context menu. I don't know why and can't find any explanation online.
Here's my tsconfig.json:
{
"compilerOptions": {
"target": "ES2020",
"module": "NodeNext",
"moduleResolution":"NodeNext",
"strict": true,
},
"include": ["public/background.ts"],
}
Here's my background.js
import * as deepl from 'deepl-node';
const authKey = "censored"; //REMEMBER TO HIDE
const translator = new deepl.Translator(authKey);
chrome.contextMenus.create({
id: "1",
title: "Translate \"%s\"",
contexts: ["selection"],
});
console.log("Context menus created yo!");
// Store the tab ID of the newly created tab
let newTabId = null;
// Listen for the creation of a new tab
chrome.tabs.onCreated.addListener((tab) => {
// Update the newTabId variable when a new tab is created
newTabId = tab.id;
});
chrome.contextMenus.onClicked.addListener((info, tab) => {
if (info.menuItemId === "1") {
// Perform the fake translation logic
const toTranslate = info.selectionText;
const translatedText = Translate(toTranslate);
// Now, open a new tab
chrome.tabs.create({
url: chrome.runtime.getURL("index.html"),
active: true,
});
// Wait for the new tab to be created and then send the message to it
const checkNewTabInterval = setInterval(() => {
if (newTabId !== null) {
// Send the message to the new tab using the unique task ID
chrome.tabs.sendMessage(newTabId, { action: "updateTranslation", text: translatedText, taskId: newTabId }, () => {
// Callback function, executed once the message is sent
console.log("Message sent!");
});
// Clear the interval as the message has been sent
clearInterval(checkNewTabInterval);
}
}, 100); // Adjust the interval as needed
}
});
function Translate(TextToTranslate) {
const translation = translator.translateText(TextToTranslate, null, 'es'); //Null means source language will be autodetected
return translation;
}