There is this SO question similar to my question - Send message to background page, update the html, and then show it in a tab. But I'm first running a JS script in the context of the current tab i.e., this script to find the highlighted word is injected into the current web page. So, I'm unable to use chrome APIs.
I am trying to make a Chrome extension that fetches the meaning of the highlighted/selected word after clicking a button on the extension's popup. Here's my popup.html:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="button.css" />
</head>
<body>
<button id="meaning" type="button">Find Meaning</button>
<script src="popup.js"></script>
</body>
</html>
Here's my popup.js:
const meanButton = document.getElementById("meaning");
meanButton.addEventListener("click", async () => {
let [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
chrome.scripting.executeScript({
target: { tabId: tab.id },
function: findMeaning,
});
});
function findMeaning(){
const word = window.getSelection().toString();
// code to send the word to another HTML file that opens in a new tab
}
Let's say, I've a mean.html in my extension's directory and it is like:
<html>
<body>
<p id="para"> the answer appears here </p>
<script>
function showMeaning(wordToFindMeaning) {
const meaning = await fetch(`someAPI/${wordToFindMeaning}`);
document.getElementById('para').innerText = meaning;
}
showMeaning(word);
</script>
How do I pass the highlighted word from popup.js to this mean.html. I don't know if chrome.storage API could be used. If we use it, the word shouldn't persist in the memory after the mean.html page is opened and the word meanings are displayed.