0

I'm trying to retrieve data from the localStorage inside background.js and pass it to popup.js, but receiving the below error,

Unchecked runtime.lastError: The message port closed before a response was received.

Note: the below snippet prints the localStorage to the console of background.js chrome.storage.local.get(["dsr_db"], function (result) { console.log(result); });

popup.html

<button type="button" class="btn btn-primary" id="display-db">
    Displaye DB
</button>

popup.js

let display_db = document.getElementById("display-db");

display_db.addEventListener("click", function() {
  chrome.runtime.sendMessage({greeting: "display-db"}, function(response) {
    alert(response.message);
  });
});

backgroun.js

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
  if (request.greeting == "display-db") {
    chrome.storage.local.get(["dsr_db"], function (result) {
      sendResponse({ message: result });
    });
  }
});

Any workaround which could be made inside background.js to make the connection long enough and pass the localStorage object to popup.js??

Thanks in advance

wOxxOm
  • 65,848
  • 11
  • 132
  • 136
Ajay
  • 11
  • 2
  • According to the docs, (https://developer.chrome.com/docs/extensions/mv2/messaging/) adding `return true` to the `onMessage` event handler will make the response asynchronous. – H K Jul 08 '21 at 11:53
  • @HK - Guess this would be the expected code : `chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) { if (request.greeting == "display-db") { sendResponse({ message: db }); return true; } }); ` I know I'm wrong here, cuz getting the same error >Unchecked runtime.lastError: The message port closed before a response was received. – Ajay Jul 08 '21 at 14:35
  • Tried inside the **try**, **catch** block to assign the value to localStorage. It worked ! – Ajay Jul 08 '21 at 14:53
  • I'm glad it's working for you. Just in case anyone else comes here. The `return true` should be after the closing bracket of the if statement. – H K Jul 08 '21 at 15:18
  • Simply read the storage in the popup, there's no need for the background script here. – wOxxOm Jul 08 '21 at 20:05

0 Answers0