I encountered an issue with my Chrome extension that I need help resolving. I am attempting to send messages from background.js to my content script. The first message goes through smoothly, but the second one results in the following error:
_generated_background_page.html:1 Unchecked runtime.lastError: The message port closed before a response was received.
It is crucial for me to receive a response from the content script after the initial message is received. This is necessary in order to remove the event listener from webRequest.onCompleted
, as failing to do so could lead to a loop problem with message passing. I'm uncertain if I am handling things correctly, especially with the removeListener
function.
Below is the code snippet where assistance would be greatly appreciated:
contentScript.js
const m3u8 = new M3U8();
console.log(m3u8);
chrome.runtime.onMessage.addListener( message => {
console.log(message);
chrome.runtime.sendMessage({status: 'ok'})
const download = m3u8.start(message.url);
download.on("progress", progress => {
console.log(progress);
}).on("finished", finished => {
console.log(finished);
}).on("error", error => {
console.log(error);
});
});
background.js
const sendURL = (request) => {
chrome.tabs.sendMessage(request.tabId, {url: request.url}, response => {
if( response.status === 'ok' ){
chrome.webRequest.onCompleted.removeListener( sendURL )
}
return true;
})
}
chrome.webRequest.onCompleted.addListener( request => {
console.log(request);
sendURL(request)
},{
urls: ["https://*.myurl.net/*/*prog_index.m3u8*"],
types: ["xmlhttprequest"]
},["responseHeaders"]);