Message port in Chrome extension has been closed without receiving a response

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"]);

Answer №1

Your attempt to send a new message, rather than a response, was unsuccessful due to the absence of a corresponding onMessage in the background script.

To address this issue, it is recommended to refer to the simple messaging example for guidance.

  1. Ensure to include the sendResponse parameter in onMessage:

    chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {  
    
  2. Utilize sendResponse instead of chrome.runtime.sendMessage

    chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {  
      sendResponse({status: 'ok'});
      //.........
    });
    

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Leverage the power of Node.js by utilizing http.get along with

I have been working on integrating a library (available here) into my project, which is capable of generating QR codes and various other types of codes. My current issue revolves around making a request where I can access both the req and res objects in o ...

Trouble with radio button selection using onclick event in Bootstrap

I've been attempting to implement an onclick event with radio buttons in Bootstrap, but unfortunately the event isn't triggering. Here's the code I'm using: <input type="checkbox" onclick="alert('Scenery!')"/> However, ...

JSONP request resulted in a syntax error

I'm having trouble retrieving data from a JSONP source, as it keeps throwing a Syntax error when the function is called. I am quite new to this subject and find it hard to understand why this error occurs. It seems like my understanding of JSONP reque ...

Guide on showcasing the most recent four blog entries using JSON API within a div element

How can I showcase only the most recent four blog posts from the WordPress API on my HTML website? HTML: <div id="content" class="content"></div> JavaScript: <script> $(document).ready(function() { $.getJSON("https://startupet.c ...

Finding repeating elements in an array of objects

Is there a way to identify duplicates in an array based on type, name, and size, increment the amount, and then remove the duplicate entries? [ { "name": "Pizza with pepper", "imageUrl": "...", ...

mongoose.js now prevents update methods from returning documents

Is it feasible to avoid fetching any data from the database after performing the SOME_MODEL.findOneAndUpdate() operation? I could potentially utilize the lean() and select() methods. However, all I really require is a callback confirming the successful up ...

Aligning a lowercase "i" element within a container

Is there a more effective way to center the "i" element within this div without using specific pixel margins that adjust based on hover? Below is my code snippet: HTML: <div class="nav-collapse"> <i class="fa fa-bars fa-2x" id="bars"></ ...

Struggling to get moment().utc() to display a two-digit format for the month and year

Currently, I am tackling a bug that has surfaced in a birthday component within my application. This component pulls the date of birth from its props in the format 1997-08-16T00:00:00Z. The challenge I am facing is that when the date of birth is set in the ...

I have an array in JavaScript containing data objects within curly braces, and I want to disregard it

In trying to sum all values for each key in an array and create a new array with the key-total pairs, encountering difficulties when dealing with empty data represented by {}. To address this issue, attempting to validate that the data is not equal to {} b ...

Customizing the appearance of Previous and Next elements using JavaScript

My challenge involves working with a form on a webpage where I do not have direct access to the HTML or CSS. Therefore, any modifications need to be made using JavaScript\JQuery. The form in question has a layout like this: https://i.sstatic.net/Czuo ...

"Efficiently sharing information in a multi-tenant application: strategies for seamless data transfer between front

In my development of a multi tenancy application using Node.js/Mongoose and React, I made the decision to utilize a single database for all users. The main collection, dubbed companies, serves as storage for basic company data and includes a unique compan ...

When using `defineModel` in Vue, the returned value can be either an object or

defineModel() is a new feature introduced in Vue 3.4+. The official documentation provides the following example: const model = defineModel() model.value = 'hello' Initially, it appears that model is an object with a value property. However, th ...

Tips for finishing a row of images using CSS3

Here is the code snippet that I am currently working with: <div id="images" class="img"/> <img src="spiderman.png" alt=""/> <img src="superman.png" alt="" height="25%" width="25%"/> <img src="batman.png" alt="" /> </div> ...

Rendering cannot occur because the data has not been set

var DialogController = function ($scope, configFac, $q) { var placeholders = []; var varInit = function () { $q.all([configFac]).then(function (response) { $scope.configResources = response[0]; placeholders[0] = resp ...

Establishing a standard flatiron-director route (within the element) using the polymer core-pages component

This particular query is closely linked with issues surrounding the usage of flatiron-director/core-pages SPA in conjunction with route-specific JavaScript functions and default routes. While the solution proposed may be effective, my limited expertise in ...

Troubleshooting multiple element visibility problems with jQuery

Please take a look at the code snippet below. $(document).ready(function(){ $(".like-btn").hover(function() { var rowid = $(this).attr("data-rowid"); $(".reaction-box[data-rowid='" + rowid + "']").fadeIn(100, function() { $(".reaction ...

How can I retrieve the most recent entry in supabase?

Is there a way to check the latest record of a user in Supabase using their user ID? I want to retrieve only the most recent date in descending order without fetching all records from the table. I am currently working on this project using Node.js with Exp ...

Strategies for addressing input range slider cross browser compatibility issues

I have encountered an issue with the slider track while using a customized range slider with CSS. For Mozilla, I utilized the selector for progress (-moz-range-progress) and for IE I used -ms-filler-lower and -ms-filler-upper. Although it works well for b ...

Can anyone point out where the mistake lies in my if statement code?

I've encountered an issue where I send a request to a page and upon receiving the response, which is a string, something goes wrong. Here is the code for the request : jQuery.ajax({ url:'../admin/parsers/check_address.php', meth ...

Received this unexpected error message upon reloading the page in a ReactJS application: SyntaxError: Unexpected token '<'

Every time I refresh the page, I encounter the error Uncaught SyntaxError: Unexpected token '<'. This error originates from a top-level component named <Navbar /> that I included in App.js. Oddly enough, the issue only arises upon refres ...