What is the best method for communicating between windows in an electron application?

As I embark on the journey of creating my first electron app, I kindly ask for your understanding :)

Upon clicking a button in the main Window, a new window should open displaying a JSON string. This action is captured by ipcMain:

ipcMain.on("JSON:ShowPage", function(e, item) {
    createJSONWindow(item);
})

Below is the function responsible for generating the new window:

function createJSONWindow(item) {
    let jsonWin = new BrowserWindow({
        width: 600,
        height: 800,
        center: true,
        resizable: true,
        webPreferences:{
            nodeIntegration: true,
            show: false
        }
    });
    jsonWin.loadFile("jsonView.html");

    ipcMain.on('JSON_PAGE:Ready', function(event, arg) {
        jsonWin.webContents.send('JSON:Display', item);
    })

    jsonWin.once('ready-to-show',()=>{
        jsonWin.show()
    });

    jsonWin.on('closed',()=>{
        jsonWin = null;
    });
}

Now here lies my question - when multiple JSONWindows are opened, each one receives the JSON:Display Message and updates its content. Shouldn't they operate independently? After all, jsonWin is always a new BrowserWindow, right?

I appreciate any advice you can offer.

Answer №1

There is an issue with the code snippet below:

ipcMain.on('JSON_PAGE:Ready', function(event, arg) {
      jsonWin.webContents.send('JSON:Display', item);
})

Each time a new window is created, ipcMain ends up subscribing to the same message. This results in every callback being called when ipcMain receives the 'JSON_PAGE:Ready' message, causing messages to be sent to every open window.


To address this problem, you can modify the code to use the event passed to the ipcMain handler to send the message back to the renderer process. Additionally, only subscribe once outside of the createJSONWindow function as shown below:

ipcMain.on('JSON_PAGE:Ready', function(event, arg) {
      e.sender.send('JSON:Display', item);
});
function createJSONWindow() { ... }

If 'JSON:Display' is intended to be sent upon page load, you can alternatively subscribe the window's webContents to the did-finish-load event which triggers when the page has completed loading.

jsonWin.webContents.on("did-finish-load", () => {
    jsonWin.webContents.send(...);
});

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

Implementing multiple perspectives on a single webpage by keeping track of the browsing history with AngularJS and leveraging the

Within my AngularJS application, I have an about page that contains various sub-sections, all within the same template. My goal is to have each section accessible through its own unique URL that will automatically scroll down to the corresponding section i ...

Using browserify "require" in console: A step-by-step guide

My Rails project now includes the browserify and pinyin packages, thanks to the browserify-rails installation. To find out more about the pinyin package, check out this link: https://github.com/hotoo/pinyin var pinyin = require("pinyin"); console.log(pin ...

What is the best way to implement rotation functionality for mobile devices when dragging on a 3D globe using D3.js and an HTML canvas?

I have been experimenting with the techniques demonstrated in Learning D3.js 5 mapping to create a 3D globe and incorporate zoom and rotation functionalities for map navigation. Here is the function that handles both zooming and dragging on devices equipp ...

Attempting to iterate over an array and utilize a foreach loop to return several sets of data

In my original code, getProductInfo took two parameters (res, sku). However, I now want to pass a set object containing SKU numbers and for each SKU, send the data using res.send. const activeProductBank = new Set([6401728, 6430161, 6359222, 6368084]); g ...

Troubleshooting issue with asp.net jquery datepicker functionality

Having recently delved into the world of JavaScript and jQuery, I'm encountering some issues that I can't seem to resolve. My gut feeling is that the problem lies in the reference to the jQuery files not working properly, but I could be mistaken. ...

Unexpected Error: Ionic Platform Commands Encounter 'Cannot read property 'split' of undefined' Issue

I have been using the same ionic application for about 4 to 5 months now. Today, I released an update to the app store and had to make some adjustments to my environment in order to compile it successfully. Strangely, when I try to run ionic platform add ...

Express is throwing an error indicating that the specified route cannot be found. Is there a way to dynamically

After dynamically adding routes and sending a post request through Postman, I encountered a "not found" error message. In the app, a 404 is logged next to the endpoint, indicating that Express cannot locate it. However, I know that I added the router dynam ...

VueJS - Building a Form Template Within a Modal Component

Struggling to include a template in a modal and unsure how to pass variables to the child template: Below is the main HTML for the application: <div id="example" class="container"> <button class="btn btn-primary" type="button" @cli ...

Searching for MongoDB / Mongoose - Using FindOneById with specific conditions to match the value of an array inside an object nestled within another array

Although the title of this question may be lengthy, I trust you grasp my meaning with an example. This represents my MongoDB structure: { "_id":{ "$oid":"62408e6bec1c0f7a413c093a" }, "visitors":[ { "firstSource":"12 ...

Attempting to iterate over the array of objects in order to discover a match

I am currently working with an object structure that resembles the one shown in the image linked below. My goal is to compare the inner object properties (such as massing type id) with existing IDs. If there is a match, I want to retrieve the name of that ...

JavaScript and CSS content, when compared, showcase varying characteristics and functionality

I'm attempting to create a conditional statement based on comparing strings from a CSS content attribute. Here is my current code, but despite the strings being identical, the comparison returns false. CSS .right-section::before { content:" ...

Locate the nearest element below a specified element when clicked using JavaScript

I've created a dynamic form that allows users to add or delete rows, and here is the code: // HTML <div class="row"> <div class="col-xs-4"> <ul> <li><input type="checkbox"></li> <li><inpu ...

Combining SlateJS with Redux

I need to store the value of a SlateJS editor in redux instead of state, but when I modify the hasLinks method, I encounter an immediate crash with the error message: TypeError: Cannot read property 'inlines' of undefined Modified Editor&apos ...

I am attempting to get a jquery plugin to function properly on my Windows 7 Internet Explorer IE7 browser. The plugin in question can be found at http://jvectormap.owl-hollow

I'm encountering some strange issues with my Internet Explorer IE7 browser on Windows 7. The jquery plugin I am attempting to use can be found at . Unfortunately, this plugin is not functioning properly on Internet Explorer IE7 on Windows 7, but it ru ...

Navigation bar remaining fixed on mobile devices

I have been working on a bootstrap site at http://soygarota.com/blog/public After checking the code multiple times, I have added the bootstrap.min.css, bootstrap.min.js, and jQuery. However, for some reason, the header navigation is not collapsing when vi ...

Guidelines for sorting through items in Vue 3

In the past, Vue 2 allowed us to easily filter items using the | and filters syntax. However, this method is no longer supported in Vue 3. Instead, we now use the "computed" property to transform a single value into another. But what about changing values ...

Error message "No such file or directory" occurring in Node.js with specific packages

After installing two packages using npm: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9afbf6e9fbeef3fbf4daabb4aab4aab7fbf6eaf2fbb4ad">[email protected]</a> <a href="/cdn-cgi/l/email-protection" class="__cf_ ...

Implementing proper data return in MVC4 through an Ajax call

When using ajax to call an action in a controller, the code may result like this: $.ajax({ type: "POST", url: "getUserInfo.json", data: "", success: function (data) { if (data.resultInfo.resu ...

Using ChartsJs to visualize input data formatted in the German data format

I am relatively new to working with Charts.js, but I will need it to generate some visually appealing graphs for my website. In the background, I have a Django project running that calculates a specific set of numbers for me. Due to the language setting in ...

Blip Scripts: Converting JSON to JavaScript - Dealing with Undefined Arrays

I am currently working on a project to develop a bot on Blip. There are certain parts where I need to send a request to an API and then use a JavaScript script to extract elements from the JSON response. The JSON response I received from the API is stored ...