How to fix 'Unchecked runtime.lastError: The message port closed before a response was received' chrome issue?

前端 未结 17 1986
孤街浪徒
孤街浪徒 2020-12-07 08:43

I\'m using VueJS and Laravel for my project. This issue started to show lately and it shows even in the old git branches.

This error only shows in Chrome browser.

17条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-07 09:32

    Post is rather old and not closely related to Chrome extensions development, but let it be here.

    I had same problem when responding on message in callback. The solution is to return true in background message listener.

    Here is simple example of background.js. It responses to any message from popup.js.

    chrome.runtime.onMessage.addListener(function(rq, sender, sendResponse) {
        // setTimeout to simulate any callback (even from storage.sync)
        setTimeout(function() {
            sendResponse({status: true});
        }, 1);
        // return true;  // uncomment this line to fix error
    });
    

    Here is popup.js, which sends message on popup. You'll get exceptions until you un-comment "return true" line in background.js file.

    document.addEventListener("DOMContentLoaded", () => {
        chrome.extension.sendMessage({action: "ping"}, function(resp) {
            console.log(JSON.stringify(resp));
        });
    });
    

    manifest.json, just in case :) Pay attention on alarm permissions section!

    {
      "name": "TestMessages",
      "version": "0.1.0",
      "manifest_version": 2,
      "browser_action": {
        "default_popup": "src/popup.html"
      },
      "background": {
        "scripts": ["src/background.js"],
        "persistent": false
      },
      "permissions": [
        "alarms"
      ]
    }
    

提交回复
热议问题