sveltejs / svelte-devtools

A browser extension to inspect Svelte application by extending your browser devtools capabilities
https://chromewebstore.google.com/detail/svelte-devtools/kfidecgcdjjfpeckbblhmfkhmlgecoff
MIT License
1.45k stars 77 forks source link

Avoid persistent ports in content scripts #54

Closed bershanskiy closed 3 years ago

bershanskiy commented 3 years ago

Pass messages between content script contexts and background context via chrome.runtime.postMessage() as opposed to persistent ports. This simplifies message passing by removing pagePorts which previously had to be managed in background. Later, this will help make background non-persistent by reducing number of persistent ports. Also, add sanity checks for messages while at it.

Motivation

This removes the need for pagePorts in src/background.js to:

  1. Make code easier to read
  2. Reduce number of persistent ports which prevent background from going to sleep

This is part of #44

bershanskiy commented 3 years ago

I incorporated your feedback, rebased, and squashed commits. Here is the diff from last state of PR to present:

diff --git a/rollup.config.js b/rollup.config.js
index e288bc5..e4eebac 100644
--- a/rollup.config.js
+++ b/rollup.config.js
@@ -63,8 +63,8 @@ export default [{
   const sendMessage = chrome.runtime.sendMessage
   const postMessage = window.postMessage.bind(window)
   chrome.runtime.onMessage.addListener((message, sender) => {
-    const messageIsFromBackgroundPage = sender && sender.id === chrome.runtime.id
-    if (!messageIsFromBackgroundPage) {
+    const fromBackground = sender && sender.id === chrome.runtime.id
+    if (!fromBackground) {
       console.error('Message from unexpected sender', sender, message)
       return
     }
diff --git a/src/background.js b/src/background.js
index a5dfc80..7a87b4d 100644
--- a/src/background.js
+++ b/src/background.js
@@ -37,9 +37,9 @@ function handleToolsMessage(msg, port) {
 }

 // Receive messages from content scripts
-chrome.runtime.onMessage.addListener((msg, sender) => {
+chrome.runtime.onMessage.addListener((msg, sender) =>
   handlePageMessage(msg, sender.tab.id)
-});
+);

 function handlePageMessage(msg, tabId) {
   const tools = toolsPorts.get(tabId)