0

I am building a page action chrome extension wherein I need to send a message from content script to background page. For example, if the content script is injected on youtube.com, I first send a message from content.js to background.js to display the icon. Now, I need to send another message to background page when this tab is closed.

For content.js, I have written code similar to following:

chrome.runtime.sendMessage({todo: "showPageAction",message: someotherinfo});

window.addEventListener("beforeunload",function(e){
    chrome.runtime.sendMessage({todo: "removeTab",message: someotherinfo});
});

Although this works fine (most of the times), I get the error Uncaught Error: Extension context invalidated. I am new to this and any clarification/suggestion would be helpful.

  • Does this help/apply? https://stackoverflow.com/questions/53939205/how-to-avoid-extension-context-invalidated-errors-when-messaging-after-an-exte – Dennis Hackethal Aug 03 '20 at 08:01
  • Well, I read and tried the techniques, but it didn't quite help as of now. What I need to know first is how to send the messages as mentioned in question. – Shashwat Srivastava Aug 03 '20 at 09:01
  • Why don't you use chrome.tabs.onRemoved in the background script? – wOxxOm Aug 03 '20 at 17:18
  • @wOxxOm Is it possible to get the URL of the removed tab using this method? because that's what I need. – Shashwat Srivastava Aug 04 '20 at 05:04
  • 1
    For that you will have to keep a global variable tabUrls, which is updated in chrome.tabs.onUpdated, but that won't work with `"persistent":false` so the best solution is to use ports ([example](https://stackoverflow.com/questions/39730493/chrome-extension-detect-when-popup-window-closes) for popup but it's the same principle). Note that the event is fired automatically after the tab is closed so there'll be no way to get/pass any data from the tab. – wOxxOm Aug 04 '20 at 06:35
  • Thanks a lot @wOxxOm for the description. On a sidenote, I need to make changes in chrome storage every minute or so. Is setInterval fine for it or is chrome.alarms a better way (in background.js)? I have noticed that setInterval does not run sometimes, like when the browser is started afresh. – Shashwat Srivastava Aug 04 '20 at 07:31
  • The background script usually unloads within half a minute. See also [Persistent background page on demand or an event page that doesn't unload?](https://stackoverflow.com/a/58577052) – wOxxOm Aug 04 '20 at 09:28

0 Answers0