Chrome Extension Word Count: Selected Text Not Updating in Popup

58 Views Asked by At

I've been working on a Chrome extension that counts the number of words in selected text on a web page and displays the count in a popup. The popup is working and shows the initial word count, I'm encountering an issue where the word count remains at 0 when I select text on the page. I'm looking for a bit of help with this. Any insights, suggestions, or guidance would be greatly appreciated!

Manifest File (manifest.json):

{
    "manifest_version": 3,
    "name": "Word Counter",
    "version": "1.0",
    "description": "Counts words in selected text and displays a pop-up.",
    "permissions": ["activeTab",
    "scripting"],
    "action": {
      "default_popup": "popup.html"
          },
    "content_scripts": [
      {
        "matches": ["<all_urls>"],
        "js": ["popup.js"]
      }
    ]
}
 

Popup HTML (popup.html):

<!DOCTYPE html>
<html>
<head>
  <title>Word Count Extension</title>
  <style>
    body {
      width: 200px;
      text-align: center;
    }
  </style>
</head>
<body>
  <h1>Word Count</h1>
  <p id="wordCount">0 words</p>
  <script src="popup.js"></script>
</body>
</html>

JavaScript (popup.js):

console.log("Content script is running");

// Function to count words in the selected text
function countWords(selectedText) {
  const wordCount = selectedText.split(/\s+/).filter(Boolean).length;
  return wordCount;
}

// Handle the selection change event
document.addEventListener("selectionchange", () => {
  const selectedText = window.getSelection().toString();
  const wordCount = countWords(selectedText);
  console.log("Selected Text: " + selectedText);
  console.log("Word Count: " + wordCount);
  chrome.runtime.sendMessage({ wordCount: wordCount });
});

console.log("Popup script is running");

// Handle the message sent from the content script
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.wordCount !== undefined) {
    document.getElementById("wordCount").textContent =
      message.wordCount + " word(s)";
  }
});

I'll also mention that I'm getting the following two errors when I inspect the popup in Dev Tools:

  • Error 1 (popup.js:28): Uncaught TypeError - "Cannot read properties of undefined (reading 'onSelectionChanged')"
  • Error 2 (popup.html:1): Error handling response - TypeError: Cannot read properties of undefined (reading 'executeScript')

Additional Information:

  • I've granted the "activeTab" permission in my manifest file to access the active tab.
  • I've used "manifest_version": 3 as required for Chrome extension development.
0

There are 0 best solutions below