What is the best way to directly send a message from a panel to a page-mod's content script?

When working with a code snippet in a Firefox addon like the one below:

var pagemod = PageMod({
    include: ['*'],
    contentScriptFile: [data.url('content.js')]
});

panel = require("sdk/panel").Panel({
  width: 322,
  height: 427,
  contentURL: data.url("main.html"),
  include:["http://*/*","https://*/*"],
  contentScriptFile: [data.url('panel.js')]  
});

I recently came across some example code in a Chrome extension where they utilize

window.parent.postMessage(message, "*")
to send messages and
window.addEventListener("message",function (e) {//do something}
to receive them. How can I establish direct communication for message passing from "panel.js" to "content.js" within a Firefox addon?

Answer №1

The solution concept closely resembles the approach outlined in this particular answer:

  1. Keep track of message ports for each tab.
  2. When sending a message, dispatch it to all recorded ports.

In order to manage a list of ports effectively, the following code snippet is implemented:

var ports = [];
var pagemod = PageMod({
    include: ['*'],
    contentScriptFile: [data.url('content.js')],
    onAttach: function(worker) {
        ports.push(worker.port);
        worker.on('detach', function() {
            var index = ports.indexOf(worker.port);
            if (index !== -1) ports.splice(index, 1);
        });
    }
});

Now, to send a message from panel.js, simply utilize:

// panel.js
self.port.emit('message-to-tabs', 'example message');

The handling of this message must occur in the main script post creation of the panel:

panel = require('sdk/panel').Panel({
    width: 322,
    height: 427,
    contentURL: data.url('main.html'),
    include: ['http://*/*', 'https://*/*'],
    contentScriptFile: [data.url('panel.js')]  
});
panel.port.on('message-to-tabs', function(message) {
    for (var i=0; i<ports.length; i++) {
        ports[i].emit('message-to-tab', message);
    }
});

Within the content script of the tab (content.js), you can listen for this event and process it accordingly:

self.port.on('message-to-tab', function(message) {
    // Handle message appropriately
});

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

Utilizing Nuxt3's auto-import feature alongside Eslint

I'm having trouble finding an eslint setup that is compatible with Nuxt3's auto-import feature to prevent no-undef errors. I have tried various packages like @antfu/eslint-config, plugin:nuxt/recommended, @nuxt/eslint-config, @nuxtjs/eslint-confi ...

Is it necessary for a click handler to be triggered when clicking on a scrollbar?

Check out these HTML snippets: Jsfiddle <style> div { margin:20px; border: 30px red solid; padding: 20px; background-color:green; overflow-y:scroll; } </style> <div onclick="alert('div clicked');"> ...

Identifying a change in the source location of an iframe element

I am working with an iframe object that is currently set to a specific page's URL. Here is an example: <iframe src="http://en.wikipedia.org/wiki/Special:Random"></iframe> My goal is to display an alert whenever the location of the iframe ...

Ensuring User Input Integrity with JavaScript Prompt Validation

I need help with validating input from a Javascript prompt() in an external js file using HTML code. I know how to call the Javascript function and write the validation logic, but I'm unsure how to handle the prompt and user input in HTML. Do I need ...

Is it possible to extract elements from a single list and insert them onto various pages?

Currently, I am retrieving items from a list using an ajax call. After constructing the HTML content, I insert these items onto a page. Now, I want to extract the same items and display them on another page with a different style. Is there a method to conn ...

Limiting character count in jQuery using JSON

I am trying to manipulate the output of a snippet of code in my jQuery: <li> Speed MPH: ' + val.speed_mph + '</li>\ that is being pulled from a JSON endpoint and currently displays as: Speed MPH: 7.671862999999999 Is there a ...

`When utilizing $routeParams, the CSS fails to load`

Whenever I use parameters in ngRoute and go directly to the URL (without clicking a link on the site), the CSS fails to load. All my routes are functioning properly except for /chef/:id. I utilized yeoman's angular generator, and I am running everythi ...

Electron Web Workers do not have compatibility with NodeJS modules

I'm currently working on a desktop application using Electron paired with ReactJS. From the initial renderer process, I create a hidden BrowserWindow to launch another renderer process. Within this new renderer process, I set up a web worker that wil ...

Sending a parameter to a different function (on a separate webpage)

At the start of my webpage, there are two radio buttons on the first page, each with its own value. Upon clicking a link to move to the second page, a for loop is activated to grab the value of the selected button. The script has been tested and works as e ...

The unit argument provided for Intl.NumberFormat() is not valid for electrical units such as volts and joules

After attempting to localize my web application, I have run into an issue with Intl.NumberFormat not working properly with electric units such as ampere, ohm, volt, and joule. The documentation provides examples and a list of available units. Despite fol ...

Developing a Prototype for an Angular Directive

After following instructions from a question on Stack Overflow, I have updated my application configuration with the code snippet below: $provide.decorator('formDirective', function($delegate) { var directive = $delegate[0]; directive.contro ...

Developing unit tests for a module responsible for generating Json REST services

Just completed working on https://github.com/mercmobily/JsonRestStores. Feeling a bit nervous since I haven't written any unit tests yet. This module is quite complex to test: it enables the creation of Json REST stores and direct interaction with th ...

showing javascript strings on separate lines

I need assistance with displaying an array value in a frontend Angular application. How can I insert spaces between strings and show them on two separate lines? x: any = [] x[{info: "test" + ',' + "tested"}] // Instead of showing test , teste ...

Filtering data in an antd table by searching

Just starting out with React hooks, specifically using TypeScript, and I'm struggling to implement a search filter with two parameters. Currently, the search filter is only working with one parameter which is 'receiver?.name?'. However, I wo ...

How is the same-domain policy applied to popup windows that have JavaScript enabled in the URL?

Is it possible to achieve something similar to this? var w = window.open("javascript: makeAnAjaxRequest();"); I'm curious whether the Ajax request, which is triggered after the new window is opened, would be considered a cross-site request. Does the ...

Fetching JSON data from an external URL using AngularJS

Check out this URL that shows JSON data in the browser: I attempted to store the data in a variable with the following code: $http.get('http://api.geosvc.com/rest/US/84606/nearby?apikey=4ff687893a7b468cb520b3c4e967c4da&d=20&pt=PostalCode& ...

Incorporate measurement markers into the graphic (ESRI JavaScript)

Is there a way to add a scale to a single graphic in a graphics layer? I currently have all the graphics shown in the same scale, but I need each graphic to have a different scale. I added the graphics using map.graphics.add() and SimpleSymbol. Any sugge ...

Ensure the sum is recalculated whenever the input changes by using the jQuery change event

I am creating a system that requires the total values of multiple inputs to not exceed 100. I have successfully implemented this functionality, but now I need a way to automatically adjust the total if changing one input causes it to drop below 100. Here& ...

Would you like to learn how to extract data from a specific textbox using jQuery and save it to a variable when the textbox is in

Below is a textbox that I am working on: <input type="text" name="company" id="company" required /> I am trying to figure out how to use jQuery to capture the values inside the textbox whenever they are typed or selected. Despite my efforts, I hav ...

What steps should be taken to prepare data for transmission to a server in a Next.js environment?

I'm in the process of creating a website that requires authentication. I am using Next (React) and typescript for web development. My objective is to make most pages ServerSideRendered or StaticHTML. However, I encountered an issue right at the begin ...