Tips to prevent encountering the "The response was not received before the message port closed" error while utilizing the await function in the listener

I'm currently in the process of developing a chrome extension using the node module "chrome-extension-async" and have encountered an issue with utilizing await within the background listener.

In my setup, the content.js file sends a message to the background script requesting it to perform some asynchronous IO operations:

// content.js
const data = await chrome.runtime.sendMessage({param: ...})
console.log(data)

// background.js
chrome.runtime.onMessage.addListener(async (request, sender, 
sendResponse) => {
    const result  = await performIOOperation();
    sendResponse(result);
})

But unfortunately, Chrome throws errors like this:

Uncaught (in promise) Error: The message port closed before a response was received.

I believe there may be a conflict when using async/await within the listener. Does anyone have any insights on resolving this particular issue?

Answer №1

const asyncFunctionWithAwait = async (request, sender, sendResponse) => {...}

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    asyncFunctionWithAwait(request, sender, sendResponse)

    return true
})

proved effective in my case

Answer №2

Expanding on all the notes and providing further clarification based on @RomanistHere's response:

// Here are a couple of example asynchronous functions
var greet;
const whatever = async function(){
    greet = "hello";
}
const getSomething = async function(){
    return "bob";
}

// Defining a function outside the callback to make use of async/await.
const asyncFunctionWithAwait = async (request, sender, sendResponse) => {
    
    // We can now use await normally here
    await whatever();
    let name = await getSomething();
    
    // As our response function is passed through "by reference",
    // we can call it as if it were within the listener callback.
    sendResponse(greet + name)

}

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {

    // Executing within the body of this callback,
    // passing the original function through.
    asyncFunctionWithAwait(request, sender, sendResponse)

    // In accordance with:
    // http://developer.chrome.com/extensions/runtime.html#event-onMessage
    //
    // This function becomes invalid when the event listener returns, 
    // unless you return true from the event listener to indicate that you 
    // want to send a response asynchronously (this will keep the message 
    // channel open until sendResponse (3rd arg) is called).
    return true;

});

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

Ways to manage absent embedded expressions in template literals

I'm curious about the most effective way to handle expressions in a template literal. The following code functions correctly var val1 = "Hello" var val2 = "world" var template = `${val1} ${val2}!` console.log(template) However, suppose for some rea ...

ACE.js enhances website security through Content Security Policy

I've been working on setting up a helmet-csp with ace running smoothly. Here's how my helmet-setup looks: var csp = require("helmet-csp"); app.use(csp({ directives: { defaultSrc: ["'self'", "https://localhost:8000"], ...

How can I validate HTML input elements within a DIV (a visible wizard step) situated within a FORM?

I recently made a decision to develop a wizard form using HTML 5 (specifically ASP.NET MVC). Below is the structure of my HTML form: @using (Html.BeginForm()) { <div class="wizard-step"> <input type="text" name="firstname" placeholder ...

Enabling clients to access all static files from a Node.js + Express server

My index.js file serves as a node.js server : var express = require('express'); var app = express(); const PORT = process.env.PORT || 5000; var serv = require('http').Server(app); app.get('/', function(req, res) { res.sen ...

Autocomplete's `getOptionLabel` function unexpectedly returned an object ([object Object]) instead of the expected string

Currently delving into the world of ReactJS and working with @mui controls, specifically a Multiselect Dropdown with autocomplete feature. Here is the child component causing me some trouble, displaying the following error message: "index.js:1 Materi ...

Is there a way to effectively transfer both Vertex and Face normals to a Three.js shader?

It seems that the THREE.Geometry methods, .computeFaceNormals() & .computeVertexNormals(), assign values to a built-in attribute array called "normal." If I want to utilize both vertex- & face-normals in one shader, I need to: Calculate face-normals ...

Utilizing setInterval for automatic page refreshing

I've been working on a setInterval function to continuously check for new comments, select them, and post them. While it's somewhat functional at the moment, it's not behaving exactly as I intended. Currently, what happens is that every thre ...

Efficiently handling multiple JSON objects in a single PHP function

Currently, I am working on a project that involves populating two dropdown menus where the value of one depends on the other. Specifically, I have three dropdowns - one to select a class, and the other two for selecting subjects and exams based on the sele ...

Error: Attempting to create a Discord bot results in a TypeError because the property 'id' is undefined

While working on a basic Discord bot, I encountered an issue when running the -setcaps command. The error message I received was: TypeError: Cannot read property 'id' of undefined. I'm unsure about what might be causing this error. Any a ...

What is the process for adding a dot to the package.json file using the npm-pkg command?

I need help using the npm pkg set command to create a package.json file with the following structure: { ... "exports": { ".": { "import": "./dist/my-lib.js", "require": "./dist/my-l ...

Is it best practice to store irrelevant context in a separate storage when utilizing the React Context API?

In the process of developing a web app, I have chosen to utilize the React Context API for managing state globally instead of opting for Redux. Currently, I have a store folder alongside my components folder where I store the loggedIn state. As I prepare t ...

Animation triggered by scrolling is not functioning/displaying div

I'm attempting to make a div fade up when it enters the viewport by using the library found at https://github.com/michalsnik/aos Unfortunately, all that seems to happen is that the div gets hidden. In the head section of my HTML file, I've refe ...

How can I use AJAX to read an image file and display it on a Canvas?

Is there a way to read an image from my server using Ajax and then display it on Canvas? I am aware that this can be achieved by using normal image tags and canvas draw methods, as shown below: <img id="myImage" src="./ColorTable.PNG" style="display:n ...

Utilizing a form on numerous occasions prior to its submission

As a newcomer to JavaScript, I am exploring the best approach for a specific task. The task involves a form with checkboxes representing different music styles and a selector for names of people. The goal is to allow users to select music styles for mult ...

Can side effects be safely incorporated within the callback of the useState hook?

Consider this scenario: const [value, setValue] = useState(false); const setSomething = (val) => { setValue((prev) => { fn(); dispatch(action); // or any other side effect return prev + val; }); }; Is it acceptable and in line with ...

Regular expression that can be used to extract information from a text file by filtering and returning only

When I open a text file, it contains several lines like the examples below. surname australia enter name j.jonhs enter name j.cause enter name f.london enter I am seeking assistance to modify the code snippet below so that it captures the first line m ...

Button Click Not Allowing Webpage Scroll

I am currently in the process of developing a website that aims to incorporate a significant amount of motion and interactivity. The concept I have devised involves a scenario where clicking on a button from the "main menu" will trigger a horizontal and ve ...

Issue with updating the vertices in three.js EdgesGeometry is causing the Line Segments to not be updated as expected

I have created multiple three.js objects. I have observed that the 'other' objects, designed as Mesh/Geometry/Material, update as expected after calling verticesNeedUpdate() Furthermore, I have two wireframe objects that were designed in this m ...

Encountered an issue: Error message stating that a Handshake cannot be enqueued as another Handshake has already been enqueued

I am currently working on setting up a node.js server to handle POST requests that involve inserting data into two separate MySQL tables. Below is the code snippet for my node.js server: let mysql = require("mysql"); const http = require('h ...

Modify the BehaviorSubject upon clicking or focusing on the input

I have created a directive for an input field. I want to trigger a flag in another component when the input is clicked or focused upon. @Directive({ selector: '[appDatepicker]' }) export class DatepickerDirective implements DoCheck{ constru ...