Interaction between content scripts and the background page through messaging

I have successfully injected content scripts into all frames. I initiated a request from the background script and now I'm looking to receive responses from all the injected content scripts (frames).

However, at the moment I am only able to receive one response. How can I modify my code to receive responses from all content scripts?

Here is the code snippet for the content script:

chrome.runtime.onMessage.addListener(   
  function(request, sender, sendResponse) { 
    if (request.bgReq == "windowInfo")
    alert("Received bgreq: "+ window.location.host);

});

And here is the code snippet for the background script:

chrome.runtime.onMessage.addListener(function(sentWords) {
    if (sentWords.words == "injection") {
        // Send request to content scripts
        chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
            chrome.tabs.sendMessage(tabs[0].id, {bgReq:"windowInfo"});
        });
    }
});

Answer №1

To ensure proper distribution, it is important to explicitly send the information to all tabs in every window:

chrome.windows.getAll({},function(windows){
  for( var win in windows ){
    chrome.tabs.getAllInWindow(win.id, function(tabs) {
      for (var i in tabs) {
        chrome.tabs.sendMessage(tabs[0].id, {bgReq:"windowInfo"});
      }
    });
  }
});

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

Can anyone suggest a way to iterate over an object and substitute spaces in the keys?

I need to iterate through a dynamically-created object that contains properties with values. The issue is that the property names in this dynamic object contain spaces, which are not allowed in JavaScript object properties. How can I loop through this ob ...

Transforming an array of strings to integers within a GraphQL query when they are incorporated

I need help finding a solution to pass an array of strings and embed it into a query while using React and GraphQL. The issue I'm facing is that even though the parameter is accepted as an array of strings, it gets converted to a string when embedded. ...

Encountering an issue with Masonry's container.append that is causing an Uncaught TypeError: Object does not possess the filter method

I have implemented infinite scroll on my website to display images. The images are arranged using a tool called masonry. Initially, I only load 10 images into the #container div when the page loads. These images are aligned perfectly with no errors in the ...

Looking for advice on successfully implementing createMultiMaterialObject in THREE.js version r62?

I am having trouble getting createMultiMaterialObject to work as expected. My goal is to have a wireframe material displayed on top of a solid material. However, the multimaterial function only seems to display the first material in the array. Here is the ...

How can I implement a jQuery modal dialog that loads a form page with pre-existing jQuery code for Autocomplete functionality?

I am facing an issue where I have a dynamically generated form on a web page and I want to display it using the jQuery UI modal dialog. Previously, I was suggested a solution that worked when my form did not already contain jQuery UI components like Autoc ...

Update div element with a dynamic table without the use of jQuery or any other libraries

So here's the deal - I'm using a combination of javascript and php to manage questions in a database (sort of like digital flashcards for studying). Everything is running smoothly, except for one little hiccup. When I click the add question butto ...

Accessing a nested value in MongoDB: A step-by-step guide

I am working on a document where I have a category object containing fields for category name, cost, and date. My task is to retrieve categories specifically from the year "2022". The console is currently showing "[]" output, but I want it to display categ ...

Bootstrap is not being rendered by Express

As I venture into learning Express, I've come across an issue regarding the rendering of Bootstrap fonts in my application. Despite setting up the correct paths, the font appears as simple Times New Roman instead of the desired Bootstrap font when run ...

Tips for creating a unique custom UI headline using ReactJS, CSS, and bootstrap

Looking to create a design that is responsive in ReactJS using Bootstrap or CSS if needed. I need assistance with placing separators between columns and ensuring the values of each label are aligned in the same column but on the next line. The layout shoul ...

Display the option to "Delete" the link only when there are multiple images in my image collection

I am using jQuery and Ajax to remove banner images from my website. However, I want to make sure that if there is only one image left, it cannot be deleted. Each image in the list has a corresponding delete link: echo '<a class="delete j_bannerd ...

The word "await" is a special reserved keyword used to call functions within an async

Currently utilizing async-await: Whenever the function run invokes findLateastVersion, even though run function is marked as async, an error message pops up stating await is a reserved word. The findLateastVersion method returns a promise and based on va ...

A guide on incorporating a Java loop with Selenium automation

// Searching and deleting process driver.findElement(By.cssSelector("input[type='search']")).sendKeys("Diversification Rule Template"); driver.findElement(By.className("delete-template")).click(); Alert alert = driver.switchTo.alert(); Thread. ...

How can you update the background image of a particular div using the 'onclick' feature in React.JS?

Thank you for helping me out here. I'm currently working with ReactJS and facing a challenge where I need to change the background of a div from a color to a specific image URL upon clicking a button in a modal. Despite my efforts, I keep encountering ...

Is it impossible to modify an enumerable attribute within a JSON.stringify replacer function?

I'm having some trouble trying to serialize non-enumerable properties within the replacer function. Can someone point out what might be going wrong in this code snippet? Any help would be greatly appreciated. var obj = {x:1,y:2}; Object.definePrope ...

Locate the closest K points to the center of coordinates at (0, 0)

Given a list of coordinates, the task is to find the k closest coordinates to the origin. While I successfully calculated the distances between the points and the origin, determining the closest k points presented an issue. To solve this, I implemented lo ...

Looking to implement a Javascript AJAX queue system for handling cross-domain JSONP requests. Seeking guidance on how to effectively accomplish this

I have a JavaScript code that I need to convert into a queue system. Currently, the code looks messy with long chains of requests being made in a specific order. Please note that my function requests return JSON objects and setting async to false is not an ...

Transmit specific elements from an array to another array exclusively with Javascript

I have some data stored in a JSON array like this: source=[{"OperationName":"All","PrivilegeName":"Roles CRUD"}, {"OperationName":"Read","PrivilegeName":"Roles Read Delete"}, {"OperationName":"Delete","PrivilegeName":"Roles Read Delete"}, ...

The tabs in bootstrap appear to be functioning properly, but the data is not displaying as expected

Currently, I am incorporating Bootstrap into my project and I am attempting to include a Twitter Bootstrap tab. I have already added jQuery and bootstrap-tabs.js to my project. Below is the script that I have added: <script> $('#myTab a&apos ...

Can you explain the distinction between mutation and action?

Can you explain the rationale behind Vuex having both "actions" and "mutations?" I can see the point of components not directly modifying state, but it seems redundant to have actions trigger mutations to update the state. What sets "actions" apart from ...

Axios encountering failure in Oauth 2.0 request

While I successfully managed to interact with the Yahoo Fantasy API using Oauth 2.0 in PHP, I encountered an issue when attempting to translate my code to JavaScript using the Axios HTTP request library. Unfortunately, I am getting no response. What could ...