popup.html
<button id="go">Go</button>
<script src="assets/js/popup.js"></script>
popup.js
document.getElementById('go').addEventListener('click', async () => {
let [tab] = await chrome.tabs.query({active: true, currentWindow: true});
chrome.tabs.sendMessage(tab.id, {go: true}, (response) => {
if (!chrome.runtime.lastError) {
console.log('fine');
} else {
// This will print the mentioned error in the console
console.log(chrome.runtime.lastError);
}
});
});
content-script.js
chrome.runtime.onMessage.addListener(async (request, sender, sendResponse) => {
// It returns the object correctly // {go: true}
console.log(request);
if(request.go) {
// This causes the error.
// When I remove this line, `fine` will be printed in the console from the `if` in the `popup.js` file above.
const go = await chrome.storage.local.get('something');
console.log(go);
}
});
And I have nothing in my background.js.
The issue is that it returns the error: The message port closed before a response was received when clicking on the start button.
I have added return true and sendResponse({status: true}) either, but didn't work!
Why do these happen and how to fix them?