chrome-extension-cli icon indicating copy to clipboard operation
chrome-extension-cli copied to clipboard

"Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist." until pages are reloaded after loading extension

Open pmorch opened this issue 1 year ago • 0 comments

Hi,

Thank you for an excellent starting point for creating an extension.

Symptom

I noticed that if I start from a browser without my new extension installed and with open pages, load the extension, and then try to use it on these "old" pages, I see this error in the Extensions page:

image image

Which corresponds to this error in the popup's console: image

It also happens if I reload the extension when an unpacked extension has been unpacked, and I presume the same thing would happen when the extension gets upgraded after having been installed properly.

Problem

As pointed out in this answer the problem is that the "old" pages that were loaded before the extension got installed/reloaded have not been reloaded, so the content script is not present on the pages. This was confirmed by seeing the symptom disappear after I had reloaded the page and then tried using the extension again.

(Partial?) Fix

I'm guessing a real fix - making the extension work on all pre-existing pages after installation/reloading - isn't possible.

If I make this diff to my vanilla extension:

diff --git a/src/popup.js b/src/popup.js
index 40f4448..0adb6f5 100644
--- a/src/popup.js
+++ b/src/popup.js
@@ -71,11 +71,12 @@ import './popup.css';
               payload: {
                 count: newCount,
               },
-            },
-            (response) => {
-              console.log('Current count value passed to contentScript file');
             }
-          );
+          ).then((response) => {
+            console.log('Current count value passed to contentScript file', response);
+          }).catch((error) => {
+            console.log('Error passing current count value to contentScript file', error);
+          })
         });
       });
     });

Now I see this in the popup's console:

Error passing current count value to contentScript file Error: Could not establish connection. Receiving end does not exist.'}

and no error in the extension page. Still not perfect. But a little better.

Better error handling for all three invocations of sendMessage methods seems like a good idea in any event (pun intended). See chrome.tabs.sendMessage and chrome.runtime.sendMessage

pmorch avatar Apr 09 '23 07:04 pmorch