Search code examples
javascriptchrome-extension-manifest-v3

chrome.runtime.sendMessage from webpage to chrome extension not return


My Chrome extension mv3 receives messages from webpage and replies to it. Here are the codes in webpage to send message to extension:

chrome.runtime.sendMessage(chromeExtensionId,
            {
             "Message": "Hello",
             "Data":
             {
              "Name": 'Jason'
             }
            },
            function(response) {
             console.log("chrome.runtime.sendMessage", response);
           });

and codes in extension's background.js to receive message and reply with true/false:

chrome.runtime.onMessageExternal.addListener(function(message, sender, sendResponse) {
    console.log(message, sender));
    sendResponse(true);
  });

manifest.json:

{
   "background": {
      "service_worker": "background.js"
    },
   "action": {
      "default_icon": {
         "16": "images/logo16.png",
         "32": "images/logo32.png"
      },
      "default_title": "My Extension"
   },
   "content_scripts": [ {
      "all_frames": true,
      "match_about_blank": true,
      "js": [ "util.js", "contentscript.js" ],
      "matches": [ "http://*/*", "https://*/*" ],
      "run_at": "document_end"
   } ],
   "description": " ",
   "externally_connectable": {
      "matches": [ "https://*.mysite.com/*", "http://*.mysite.com/*" ]
   },
   "icons": {
      "128": "/images/logo128.png",
      "16": "/images/logo16.png",
      "32": "/images/logo32.png",
      "48": "/images/logo48.png"
   },
   "manifest_version": 3,
   "name": "My Extension",
   "permissions": ["cookies", "tabs", "proxy", "alarms", "storage", "downloads", "webRequest", "notifications", "nativeMessaging", "clipboardRead", "clipboardWrite", "declarativeNetRequest","declarativeNetRequestFeedback" ],
   "host_permissions": ["<all_urls>"],
   "version": "4.0.7"
}

Most of the time it works fine.

The only problem is when i set my webpage as startup page of chrome, which means the page is opened immediately when chrome starts, sendMessage does not return and console.log in both sender and receiver sides are not printed. There is no error output in console either. It looks like codes freeze inside sendMessage. What's going on there?


Solution

  • It's a known problem. Chrome intentionally delays extensions at browser startup to show the active tab faster. The workaround is to repeat sendMessage:

    send('abcdefgkhgghfg........', {foo: 'bar'}, res => {
      console.log('response', res);
    });
    
    function send(extensionId, msg, callback, retry = 20) {
      const timer = setTimeout(send, 100, extensionId, msg, callback, retry - 1);
      chrome.runtime.sendMessage(extensionId, msg, response => {
        if (!chrome.runtime.lastError || !retry) {
          clearTimeout(timer);
          callback(response);
        }
      });
    }