0

This post is connected to my previous post. I am creating a Chrome extension. I want to insert text into the Gmail reply field - based on a click. I use MutationObserver for getting the changes and not only the initial HTML. Since I implemented MutationObserver I get the error:

content.js:63 Uncaught Error: Extension context invalidated. at HTMLDocument.<anonymous> (content.js:63:20)

Like its stated here. I tried to insert if (chrome.runtime.id == undefined) return; for avoiding the error. But it's not working. Where do I need to add the insert if (chrome.runtime.id == undefined) return;?

content.js

document.addEventListener("click", (event) => {
  if (event.target.innerText == "Reply") {
    const element = document.querySelector(".a3s.aiL");
    const textContent = element.textContent;
    const allElements = document.querySelectorAll("*");
    const observer = new MutationObserver((mutations) => {
      const insertField = allElements.forEach((element) => {
        if (element.classList.contains("aO7")) {
          console.log("found it");
        }
      });
    });

    observer.observe(document.body, {
      attributes: true,
      childList: true,
      subtree: true,
    });

    chrome.runtime.sendMessage({
      type: "click_event",
    });
  }
});

background.js

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
  if (request.type == "click_event") {
    console.log("click event captured in current webpage");
  }
});
Max Hager
  • 536
  • 4
  • 13
  • You can wrap the call that sends the message `chrome.runtime.sendMessage(..)` in the content script in an `if` statement that checks for this condition. – Titus Dec 12 '22 at 19:37
  • Hm okay, still same error. @Titus – Max Hager Dec 12 '22 at 19:39
  • 1
    You probably still have some content scripts injected in that page that don't have this check. After you make this change, you'll have to refresh the extension and then refresh the webpage the content script is injected in. – Titus Dec 12 '22 at 19:42
  • The check should be inside MutationObserver callback. – wOxxOm Dec 12 '22 at 21:07

0 Answers0