Exchange information among scripts in the background environment, such as the background script, browser action, page action, options page, and more

I am facing a challenge with transmitting data from my background script to the script for my pageAction. The content script I have adds an <iframe />, and the JavaScript within the <iframe /> successfully receives the data from the background script, but it appears that the data is not being retrieved in my pageAction.

In the background script, my code looks something like this:

chrome.tabs.sendMessage(senderTab.tab.id, 
{
   foo:bar
}); 

where senderTab.tab.id acts as the "sender" in the onMessage listener within my background script.

The JavaScript loaded by the <iframe /> injected by my content script includes code similar to:

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
      console.log("received in iframe:", request);
    }   
});

The <iframe /> successfully receives the message as expected.

I included the same JavaScript in my page_action.js, but it does not receive any data from the background script. The pageAction is triggered using

chrome.pageAction.show(senderTab.tab.id);
before calling
chrome.tabs.sendMessage(senderTab.tab.id ...

Is the HTML page associated with my pageAction not part of the same tab? Given that this tabId allows me to activate/"show" the icon, I would expect the JavaScript listener for the pageAction to also receive information from

chrome.tabs.sendMessage(senderTab.tab.id ...


In my content script, I use the following method to send data to the background script:

chrome.runtime.sendMessage({
  foo: bar
});  

When the content script sends the above message, the pageAction JavaScript is able to retrieve it.


How can I ensure that the background script effectively transmits data to my pageAction? I prefer not to rely on pageAction requesting or polling, rather I want pageAction to simply listen and receive updates. For instance, if the pageAction's HTML is displayed, it should be capable of updating in real time as the background page implements changes.

Answer №1

Interacting with a Page in the Background Context

When it comes to communicating with pages open in the background context, you have several options:

If you want to send messages to these contexts, use runtime.sendMessage(). Remember that the scope for these contexts only exists when displayed.

  • Direct Communication: You can directly change variables or call functions from one page in the background context to another using methods like extension.getViews().
  • Messaging: Use runtime.onMessage and chrome.runtime.sendMessage() to receive and send messages between scripts.
  • StorageArea: Store data in a StorageArea and be notified of changes in other scripts using chrome.storage.onChanged.

The best method depends on what you're trying to communicate and where you're sending the message from in your extension.

More about Popups

Popups like browser actions and page actions are not directly associated with active tabs but exist in the background when visible. Only one popup is open per Chrome window.

You can programmatically open new tabs/windows with HTML from your extension using tabs.create() or windows.create(). Just note that interacting with the newly opened page may require waiting for its DOM to load.

Additional Resources

For more information, refer to the resources provided by Chrome and Firefox developers on messaging and web extensions architecture.

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

In React, firebase.firestore() is operational, but firebase.functions() remains undefined

Currently, I am engaged in a React project that heavily relies on Firebase for various features. In order to incorporate HTTPS callable functions into the project, I encountered an issue. The problem lies in the incorrect importation of the 'firebase ...

Mongoose .lean() Method Causes Equality Test to Fail

In my quest to compare req.user._id with an array of ObjectIds obtained from a MongoDB query, I encountered failures in all my attempts using .includes(), as well as strict and loose equality checks. Below is a simplified version of the logic in my contro ...

What is the rationale behind not storing OAuth2 access tokens as HttpOnly secure cookies? How could this approach be implemented in a Node.js application?

I have a Node.js RESTful api setup where the response token received after posting to /oauth/token typically looks like this: { "refresh_token": "eyJraWQiOiI2...", "token_type": "Bearer", "access_token": "eyJraWQiOiI2Nl...", "expires_in": 3600 } ...

Creating a list that renders responsively using ReactJS

I'm currently working on implementing a responsive search bar that filters through a list of pure components (up to 100 components displayed at once). However, I've noticed there is a slight half-second delay between typing the first letter and s ...

Is it possible for ng-change to invoke another controller?

Can someone help me with the following HTML code? <div ng-controller="select"> <select ng-options="n for n in names" ng-model="selected.item" ng-change="change()"> </select> </div> <div ng-co ...

AngularJS - Oops! Looks like we encountered an error: [$injector:modulerr]

I have a client-server application and I am facing an issue with this error message: "Uncaught Error: [$injector:modulerr]". Despite searching for solutions, none of them seem to be fixing the problem. Here is my client-side code: angular.module('m ...

The $http function in AngularJS consistently returns undefined instead of the expected value

var result = dataService.makeHttpRequest("GET", "/documents/checkfilename/", null, function (response, status, headers, config) { // I can see `true` if I alert(response); here // I want to return the contents of ...

What are the advantages of using Yarn instead of NPM? Understanding the distinctions between the two package managers

What sets Yarn apart from NPM? I've been scouring the internet for articles that compare Yarn and NPM, but all I find are resources detailing the equivalent commands between the two. While both seem to offer similar functionalities, such as local cac ...

Utilize JavaScript or JQuery to create a dynamic pop-up window that appears seamlessly on the

Looking to create a unique feature on an HTML page? Want a clickable link that opens a "pop-up" displaying a specific image, right within the page rather than in a new tab or window? Ideally, this pop-up should be movable around the page like a separate ...

Exploring the properties of individual Vue components on a single page with v-for loop

Struggling to render a Vue component in a Rails app by iterating through an array of data fetched via Ajax. The Slim template (index.html.slim) for the index page includes a custom_form_item component, where items represent custom forms data from Rails and ...

jquery: displaying repeated divs on mouse hover - a tutorial

Let's say we have a div like this: <div class="y1"> <img src="i/o.png" /> </div> Also, we have this div for pre-loading: <!-- pre load --> <div class="p1" style="display:none"> <h5 class="ob">Title</h5> < ...

Transferring information from a webpage to a popup using executeScript: A guide

I've successfully retrieved data from a website, but I'm struggling to send it to popup.js. I attempted to use executeScript with a callback, but it's not working for me. popup.js function getData() { chrome.tabs.query({active: true, c ...

The browser window's location is redirected to an empty page

I'm currently working on a website that has a similar layout to this (). https://i.sstatic.net/c7I2y.png My main issue is with the code I've written to detect a click on the linkedin div and redirect accordingly. <script src="https://ajax.g ...

Accessing the background page of a Chrome extension while it's in operation

I am in the process of developing my first chrome extension that allows youtube.com/tv to run in the background so it can be accessed easily on a phone or tablet. Everything is working fine, except for the fact that if I want to watch the video and not j ...

What is the best way to establish a default selection in Angular?

After retrieving JSON data from the server, it looks something like this: $scope.StateList = {"States": [ { "Id": 1, "Code": "AL", "Name": "Alabama" }, { "Id": 2, "Code": "AK", "Name": "Alask ...

Identifying Disconnected Sockets in Socket.IO

Running a socket.io server/client setup, I encounter an issue where a client safely disconnects, the server-side code snippet socket.on('disconnect', function() { }); is triggered as expected. However, in case of a client server crash, the ev ...

What is the best way to prevent a jQuery hover event from adding a text-shadow to the CSS?

Currently, I am facing an issue with a jQuery event that triggers a text-shadow effect: $(".leftColumn").hover(function (){ $(".leftColumn h2").css("text-shadow", "0px 2px 3px rgba(0, 0, 0, 0.5)"); },function(){}); The problem arises when the text-shad ...

The name field in the request body is currently undefined

Currently, I am working on developing a basic blog page using technologies such as ejs, JavaScript, Node.js, Express, and body-parser. While working on passing inputs to the command line, specifically for the title, I encountered an issue. When I used req ...

Tips for configuring VS Code to display and check object schemas

npm init -y npm i axios npm i @types/axios --save-dev Why doesn't VS Code 1.62 seem to provide the response object schema when typing code like this: resp = await axios("https://httpstat.us/404"); resp. <C-Space> displays confusing / inappropr ...

Troubleshooting problem with video recording functionality using HTML 5 media streams

My HTML 5 code for video recording and uploading is encountering a JavaScript error when the start button is clicked. The error messages I am receiving are: "TypeError: webcamstream.record is not a function streamRecorder = webcamstream.record();" "TypeE ...