Google Chrome extension: Communicating from injected content script to background script

/* My Unique Background Code */
console.log("Initializing the Background ! ");
chrome.runtime.onMessageExternal.addListener(
    (request, sender, sendResponse) => {
        console.log("A message has been received");
        console.log(request);
        console.log(sender);
    }
);
    // Injecting script into the page
chrome.webNavigation.onCompleted.addListener((details) => {
    chrome.tabs.executeScript(details.tabId, {
        file: "include/ts/injectScript.js",
        runAt: "document_end"
    });
}, {url: [{urlPrefix: "https://website.com"}]});
console.log("Finished Initializing the Background");

/* My uniquely injected script code */
    var extensionID = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    chrome.runtime.sendMessage(extensionID, {test : 123},(response) => {
        console.log(response);
    });

/* A snippet of my manifest.json file (with correct URL configuration) */
"externally_connectable": {
    "matches": [
      "*://*.example.com/tests/*"
    ]
 },
 "permissions": [..., "*://*.example.com/tests/*",...]

The background automatically injects a JS script when the page loads.

All tests conducted in the console (on the current page) are successful, and the background is able to receive messages.

Unfortunately, even though the background successfully injects the script upon page load, it is not receiving any messages.

Apologies for any language errors, Thank you in advance for your assistance

Jérémy-F

Answer №1

To receive messages from your own content scripts, make sure to utilize

chrome.runtime.onMessage.addListener
rather than
chrome.runtime.onMessageExternal.addListener
.

chrome.runtime.onMessageExternal should be used for receiving messages from other extensions or apps.

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

Modifying elements within a JSON array-generated list

As a beginner in JavaScript, I have encountered an issue with my code. It dynamically creates a list from a JSON array called rolesData and displays the data from "roles" in a list based on a random selection (using document.body.appendChild(createList(rol ...

Embracing efficiency by streamlining jQuery selectors

I currently have this piece of code and it's functioning properly: $(document).delegate("tr.updating input, tr.updating a, tr.updating label", 'click', function(event){ It would enhance the readability to reduce repetition by using somethi ...

Starting Web Server using File (file://) protocol

I'm currently using Quasar to develop a Vue SPA web app/page. For this project, the web app will only run by clicking on the index.html file generated by the Quasar packager. This package will not be distributed online or hosted on any domain. My mai ...

PrimeNG Template not showing the form

I have integrated a form into PrimeNG's turbotable to allow users to create a new entry (group) in the table located within the footer. However, the form is not being displayed as expected. Can you help me troubleshoot this issue? <ng-template pTe ...

Can you show me how to recreate a 502 gateway timeout error?

Looking for suggestions on how to create a page that exceeds 600 seconds to load? Any tips on triggering a 502 gateway timeout error would be helpful as well. ...

Ensuring input integrity in Lit and Typescript for customized elements

I have been developing custom web controls using TypeScript and Lit, including submit buttons and inputs. However, I am experiencing difficulties when trying to wrap them in a form within my HTML. The inputs are not visible to the form, and the submit bu ...

Could converting a 47-byte JSON string into 340 MB be possible through JSON stringification?

var keys = [7925181,"68113227"]; var vals = {"7925181":["68113227"],"68113227":["7925181"]}; var temp = []; for (var i = 0; i < keys.length; i++) { temp[keys[i]] = vals[keys[i]]; } //alert(JSON.stringify(vals).length); alert(JSON.stringify(temp).le ...

What is the best way to bring a nested object to the top level without deleting the original top level

Imagine having the following dataset: data = [{ "_id" : "2fApaxgiPx38kpDLA", "profile" : { "name" : "Karina 1", "avatar" : "avatar1.jpg", "bio" ...

tabs that are vertical without the use of jQuery UI

I'm feeling a bit lost because I can't seem to find any examples or tutorials for vertical or side tabbed content. I want the tabs to be on the left side, but all my searches online have come up empty. Maybe I'm not using the right search te ...

Utilizing a mouse-over script for image popup alignment

I recently came across the mouse over script below on a website, and I must say it works really well and is very easy to use. The only issue I have with it is the placement of the image. Currently, the image follows the cursor as it moves. Question: Is th ...

webpack: the necessity of running TSC before resolving modules manually

Below is my complete webpack.config.js file for reference. If I delete all the *.js files in the app directory, webpack throws the following error: ERROR in ../main.ts Module not found: Error: Can't resolve './app/app.module' in 'C ...

What is the process for integrating ng-bootstrap into an Angular 5 project?

Has anyone encountered issues loading ng-bootstrap in their Angular project? I'm experiencing difficulties and would appreciate any insights. Thank you for your help! This is my app.module.ts file: import { BrowserModule } from '@angular/platf ...

What methods can I use to create fresh metadata for a search inquiry?

On my search page, I am using a search API from OpenAI. My goal is to modify the meta description of the page to display 'Search | %s', with %s representing the decoded search query. However, due to limitations in Nextjs 13, the useSearchParams f ...

Tips for accessing nested array data using jQuery DataTables

Here is the JSON data I am working with: { "00100": { "claim_id": "21", "reference_no": "00100", "distributor_name": "Standard Match", "group_name": "A", "month": "Jun2017", "grand_total": "268.532", "details": [ { ...

Tips on tallying the frequency of items in a state array

I'm currently working on an application in which clicking a button adds the item's value to the state. The button is clickable multiple times, allowing the same item to be added multiple times in the state array. My current code snippet: export ...

Calculate the total number of blank input boxes within a specific row of the table

What is the method to count the number of input boxes without a value in a table row using jquery? For instance: <table id="table1"> <tr class="data" id="row5"> <td><input type="text" value="20%" /></td> <td><input ...

Unit tests are failing to typecast the Angular HTTP GET response in an observable

I've been delving into learning about unit testing with Angular. One of the challenges I encountered involved a service method that utilizes http.get, pipes it into a map function, and returns a typed observable stream of BankAccountFull[]. Despite ...

Calculate the number of rows in a table that contain identical values

I have a puzzling issue that has been on my mind. I currently have an SQL statement that selects specific rows from my database and displays them in an HTML table, which is functioning properly. However, I now need to determine how many rows have the same ...

Challenges arise when building a package while importing all modules on external servers

While exploring Three.js within a React application, I have created an example that functions properly when tested locally; however, it fails to load when accessed remotely from static hosts like GitHub or Amazon S3. When I run my GitHub project locally, ...

What is the best way to establish a model using a date index?

I'm trying to access an API using Angular that returns an array with dates as indexes. After attempting to create a model, I encountered some issues. How should I modify it? This is what the API response looks like: { "Information": { " ...