In my code I have a content script which requests a cookie from the background script.
Even though I can print the cookie to the Dev Tool console, the message received from background script is always undefined.
Why?
Background script:
// listens for content scripts to request the cookie
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
// Respond with the value of the cookie
if (message === 'get-cookie') {
chrome.cookies.get({"url": "http://www.example.com", "name": "cookie_example"}, function(cookie) {
// prints the correct value
console.log(cookie.value);
sendResponse(cookie.value);
});
}
});
}
});
Content script:
chrome.runtime.sendMessage('get-cookie', (response) => {
// logs "undefined"
console.log(response);
/* tries to do something useful with the response */
});
And returns an error
Unchecked runtime.lastError: The message port closed before a response was received