the message sent from a webpage to a Chrome extension using chrome.runtime.sendMessage does not receive

My Chrome extension, mv3, has the capability to receive messages from webpages and respond accordingly. Below are the code snippets that enable the webpage to send a message to the extension:

chrome.runtime.sendMessage(chromeExtensionId,
            {
             "Message": "Hello",
             "Data":
             {
              "Name": 'Jason'
             }
            },
            function(response) {
             console.log("chrome.runtime.sendMessage", response);
           });

and here are the codes within the extension's background.js file to handle incoming messages and reply with true/false:

chrome.runtime.onMessageExternal.addListener(function(message, sender, sendResponse) {
    console.log(message, sender));
    sendResponse(true);
  });

The manifest.json file contains essential configurations for the extension:

{
   "background": {
      "service_worker": "background.js"
    },
   "action": {
      "default_icon": {
         "16": "images/logo16.png",
         "32": "images/logo32.png"
      },
      "default_title": "My Extension"
   },
   "content_scripts": [ {
      "all_frames": true,
      "match_about_blank": true,
      "js": [ "util.js", "contentscript.js" ],
      "matches": [ "http://*/*", "https://*/*" ],
      "run_at": "document_end"
   } ],
   "description": " ",
   "externally_connectable": {
      "matches": [ "https://*.mysite.com/*", "http://*.mysite.com/*" ]
   },
   "icons": {
      "128": "/images/logo128.png",
      "16": "/images/logo16.png",
      "32": "/images/logo32.png",
      "48": "/images/logo48.png"
   },
   "manifest_version": 3,
   "name": "My Extension",
   "permissions": ["cookies", "tabs", "proxy", "alarms", "storage", "downloads", "webRequest", "notifications", "nativeMessaging", "clipboardRead", "clipboardWrite", "declarativeNetRequest","declarativeNetRequestFeedback" ],
   "host_permissions": ["<all_urls>"],
   "version": "4.0.7"
}

In most cases, the extension functions properly.

However, there is an issue when setting my webpage as the startup page for Chrome, causing the sendMessage method to not return, and no output is displayed in the console logs of both the sender and receiver sides. There are no error messages being generated either. It appears that the execution freezes within the sendMessage function. What could be causing this behavior?

Answer №1

This issue has been identified as a common problem in Chrome. The browser intentionally delays extensions during startup to prioritize displaying the active tab quickly. One possible solution is to use the sendMessage function repeatedly:

send('abcdefgkhgghfg........', {foo: 'bar'}, res => {
  console.log('response', res);
});

function send(extensionId, msg, callback, retry = 20) {
  const timer = setTimeout(send, 100, extensionId, msg, callback, retry - 1);
  chrome.runtime.sendMessage(extensionId, msg, response => {
    if (!chrome.runtime.lastError || !retry) {
      clearTimeout(timer);
      callback(response);
    }
  });
}

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

Arrangement of 3 points on the graphical user interface

Seeking the orientation of 3 ordered points in space using an algorithm discovered on this site: https://www.geeksforgeeks.org/orientation-3-ordered-points/ Desiring to display the orientation on GUI as Clockwise or CounterClockwise while adjusting coordi ...

Using ng-bind-html does not offer protection against cross-site scripting vulnerabilities

I utilized ng-bind-html to safeguard against cross site scripting vulnerabilities. I came across information about sanitization and engaged in a discussion at one forum as well as another informative discussion. However, I encountered an issue where it di ...

Display the item prior to fetching the AJAX response

Whenever a user clicks on my button, I want to display an item that is connected with my AJAX response. The div should be visible after clicking the button and then hidden once the entire page has finished loading. This is my AJAX code: document.getEleme ...

My controller in AngularJS is having trouble fetching the latest values of the $scope variables

In my code, I've included the relevant snippet below. The base angularJS seems to be functioning properly as the HTML document doesn't display {{}} variables but instead remains blank. I suspect that this is due to the variables receiving a null ...

The directive in an Angular app is not loaded due to lazy loading

Seeking assistance with lazy loading a directive in my Angular application, I am using ui.router and oc.lazyLoad. Below is the code snippet: menu : <ul> <li><a ui-sref="home">Home</a></li> <li><a ui-sre ...

Updating the FormArray index using Angular's `removeAt(i)` function does not reflect changes in the DOM

I initially suspected that there was an issue with my implementation, but it appears that the code I used to create a dynamic FormArray should be working, as indicated in this question I posted. However, when I integrate it into my project, the remove func ...

What is the most effective method of testing with jest to verify that a TypeScript Enum list contains all the expected string values?

Recently, I created a list of enums: export enum Hobbies { Paint = 'PAINT', Run = 'RUN', Bike = 'BIKE', Dance = 'DANCE' } My goal is to iterate through this list using Jest and verify that all the string ...

How can I implement jQuery autocomplete with customized settings?

In my Drupal project, I am looking to implement jQuery's auto complete feature to search for nodes based on their titles. I am having trouble finding examples that align with my specific requirements: The URL structure should be: /api/node/title/{wh ...

Invalid Syntax: The token '21' is found unexpectedly at column 12 in the expression [2013-08-28 21:10:14] beginning at [21:10:14]

I'm in the process of creating a straightforward directive for a date countdown. However, I've hit a roadblock with this particular error: Syntax Error: Token '21' is an unexpected token at column 12 of the expression [2013-08-28 21:10 ...

Is the for loop in Node.js completed when making a MySQL call?

A certain function passes an array named res that contains user data in the following format: [ RowDataPacket { UserID: 26 }, RowDataPacker { UserID: 4 } ] The goal is to create a function that fetches each user's username based on their ID and stor ...

The yarn.lock file is failing to reflect the updated version of a dependency in package.json, even after running the yarn install command or simply using yarn to install the

Within the project's repository, both the package.json and yarn.lock files are already present. I am currently in the process of upgrading a specific package from version 2.0.14 to version 2.0.16. After running either yarn install or simply yarn, I n ...

Using AJAX to dynamically load Javascript

I came across this interesting code snippet: <script type="text/javascript" language="javascript"> $(function(){ $(window).hashchange( function(){ window.scrollTo(0,0); var hash = location.hash; if (hash == "") { hash="#main"; } ...

Updating and Preserving Content in Angular

I've encountered an issue while working on a code that allows users to edit and save a paragraph on the screen. Currently, the editing functionality is working fine and the save() operation is successful. However, after saving, the edited paragraph do ...

"Challenges Arising in Deciphering a Basic JSON Array

After countless attempts, I am still struggling to solve this issue. My PHP code is functioning properly, as it returns the expected data when "Grove Bow" is selected from the dropdown menu: [{"wtype":"Grove Bow","was":"1.55","wcc":"5","wbdmin":"12","wbdm ...

Removing the JavaScript unicode character 8206 from a text string

I recently transitioned from VB.NET to JavaScript, and I am still getting familiar with the language. I have encountered an issue where a string I'm working with in JavaScript contains Unicode escape characters (0x5206, left-to-right mark) that I need ...

Issue Arises in AngularJS where $scope values are not properly updating after ng-repeat loop

I am utilizing a controller that holds data to be iterated through using ng-repeat, and I am using it in conjunction with this selection model directive. However, once I use ng-repeat to generate multiple entries in the DOM, the bindings to $scope.selecte ...

I am unable to pass a variable through a callback, and I cannot assign a promise to a

Currently, I am facing a challenge with my code where I need to loop through a hard-coded data set to determine the distance from a user-entered location using Google's web API. The issue lies in passing an ID variable down through the code so that I ...

"Enhancing HTML with jQuery Autocomplete for Advanced Search Results

I am in need of an autocomplete text box for my search feature, and I have decided to implement it using jQuery UI. Utilizing an ASP.NET Core API, I will retrieve search results in JSON format. These search results must be grouped with Bootstrap collapse ...

Tips for modifying environment variables for development and production stages

I am looking to deploy a React app along with a Node server on Heroku. It seems that using create-react-app should allow me to determine if I'm in development or production by using process.env.NODE_ENV. However, I always seem to get "development" ev ...

THREE.Raycaster delivering imprecise outcomes

I am currently working on creating a 2D scatterplot with tooltips, but I am facing an issue with the raycaster not detecting when a point is being hovered over. The tooltip seems to activate only when touching an object, which is correct behavior, but it d ...