Encountering an issue while attempting to transmit Electron window data

Hey there! I'm currently in the process of transitioning my project from a web browser to a GUI-based app using electron. I came across this video which was really helpful in getting started. The tutorial uses yarn, but I prefer npm 9.2.0.

Initially, I encountered an issue where nothing happened when I clicked the button. Luckily, I found a solution in the comments suggesting a change in code:

webPreferences:{
    nodeIntegration: true,
}

I updated it to:

webPreferences:{
    nodeIntegration: true,
    contextIsolation: false,
    enableRemoteModule: true,
}

This change resulted in progress, but also led to ... an error. Frustrating, right?

Here's a snippet of my current code:

gui.js

const { app, BrowserWindow, ipcMain } = require("electron");

let leftWindow = null;
let rightWindow = null;

const createWindows = (win, page) => {
    win = new BrowserWindow({
        width: 1024,
        height: 600,
        resizable: false,
        fullscreen: true,
        webPreferences:{
            nodeIntegration: true,
            contextIsolation: false,
            enableRemoteModule: true,
        },
    });
    win.loadFile(page)
};

app.whenReady().then(() => {
    //createWindows(leftWindow, "dash.html");
    createWindows(rightWindow, "controls.html");
});

app.on('window-all-closed', () => {
    if(process.platform !== 'darwin') {
        app.quit()
    }
})

ipcMain.on('send', (event, data) => {
    const randomStr = data + Math.random().toString(36).substring(2, 5)
    rightWindow.webContents.send('receive', randomStr)
})

render.js

const ipcRenderer = require("electron").ipcRenderer;
const test = () => {
    ipcRenderer.send("send", document.querySelector(".keyWord").value);
};

ipcRenderer.on("receive", (event, data) => {
    alert(data);
    const tempTag = document.querySelector("#temp");
    tempTag.innerText = data;
});

controls.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Controls</title>
        <script defer src="render.js"></script>
        <link rel="stylesheet" href="./public/styles.css" />
    </head>
    <body>
        <div id="content">
            <input type="text" class="keyWord" placeholder="Enter Data">
            <button onclick="test()">Test</button>
            <h1 id="temp">Random String</h1>
        </div>
       <script type="text/jsx" src="./public/controlApp.jsx"></script>
    </body>
</html>

Answer №1

After following @Arkellys and checking out the links provided, I found myself lost in the electron documentation :/

Turned to Google for more insights and here is what I managed to gather on preload.js as per his suggestion

Thank you for your contribution

gui.js

const { app, BrowserWindow, ipcMain } = require("electron");
const path = require('node:path');

let leftWindow = null;
let rightWindow = null;

const createWindows = (win, page) => {
    win = new BrowserWindow({
        width: 1024,
        height: 600,
        resizable: false,
        fullscreen: true,
        webPreferences:{
            preload: path.join(__dirname, 'preload.js'),
        },
    });


    ipcMain.handle('generatePassword', (req, data) => {
        const password = data.keyWord + Math.random().toString().substr(2, 5)
        return { password }
    })

    win.loadFile(page)
};

app.whenReady().then(() => {
    //createWindows(leftWindow, "dash.html");
    createWindows(rightWindow, "controls.html");
});

app.on('window-all-closed', () => {
    if(process.platform !== 'darwin') {
        app.quit()
    }
})

preload.js

const { contextBridge, ipcRenderer } = require('electron')

contextBridge.exposeInMainWorld('electronAPI', {
    createPassword: (data) => ipcRenderer.invoke('generatePassword', data)
})

render.js

const keyWord_el = document.getElementById('keyWord');
const btn_el = document.getElementById('btn');

btn_el.addEventListener('click', async () =>{
    const keyWord = keyWord_el.value;
    
    const res = await electronAPI.createPassword({ keyWord })

    document.getElementById('passWord').innerText = res.password
})

controls.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Controls</title>
        <script defer src="render.js"></script>
        <link rel="stylesheet" href="./public/styles.css" />
    </head>
    <body>
        <div id="content">
            <input id="keyWord" type="text" placeholder="Enter Data">
            <button id="btn">Test</button>
            <h1 id="passWord">Random String</h1>
        </div>
       <script type="text/jsx" src="./public/controlApp.jsx"></script>
    </body>
</html>

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

Guide on converting JSON data into a PDF using TypeScript

I need to take JSON data and convert it into a PDF format when the PDF button is clicked in the UI. I have tried a few things but I'm struggling with binding the response to the PDF function. My goal is to display values from the "actualExpenses" arra ...

Unveiling the secrets of the Google Region Lookup API

I am struggling to incorporate the Region Area Lookup feature from Google Maps into my project. Despite it being an experimental feature, I am having difficulty getting it to function correctly. Initially, I attempted to integrate this feature into a Reac ...

Utilize PHP, JSON, and JavaScript to dynamically insert personalized information into HTML

Struggling, I turn to this site for help despite the dislike for "spot my mistake" code. My website urgently needs access to user-specific data from a PHP database, then convert that data into a JSON file and display it in an HTML header. The database cont ...

Changing $scope does not automatically refresh the selected option when using ng-options with <select> in AngularJS

My select element is structured like this: <select ng-model="exportParam" ng-options="item as item.lib for item in allExportParams | orderBy:'lib'" class="form-control"> </select> To save its state for later display, I sto ...

Issue with the reload animation jumping too quickly in Framer Motion on NextJS

While creating an animation for my landing page using NextJS with framer motion, I encountered a strange behavior after deploying the site. The animations started to happen too quickly and it felt a bit off. During development on localhost using Chrome, ev ...

Errors are being encountered by npm during the execution of tsc and concurrently when running the start command

Every time I attempt to execute npm start, a series of errors pop up on my screen... 19 error node v4.2.0 20 error npm v3.10.5 21 error code ELIFECYCLE 22 error <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6d1f081e180008400 ...

`Testing the functionality of javascript/jQuery events using Jasmine`

I came across this code snippet: $(document).on('click', '#clear-button', clearCalculatedPrice) clearCalculatedPrice = -> $('#price_rule').removeAttr('data-original-title') $('#calculated-price&apos ...

Looking for a powerful filtering menu similar to Excel or Kendo UI Grid in Datatables?

Is there a way to add Excel-like filtering to DataTables? It's surprising that such a widely used and advanced plugin doesn't have this feature already. If not, is there an easy way to implement it? Below are examples of advanced menu filters sim ...

Is there a way to transform text input into a dropdown menu that dynamically alters the rows of a table?

Currently, I am working on creating a drop-down menu selection that will dynamically change the table rows based on user input. At the moment, users can enter their input into a text field to see changes in the table rows. However, I would like to impleme ...

When deployed, Webpack 2.2.0.rc-0 will condense and optimize vendor.js and manifest.js, but will not perform the same action on bundle

I have been troubleshooting why my vendor and manifest files are minified and uglified, but my bundle is not. I am wondering if it could be related to the order of the plugins or perhaps something to do with the CommonsChunkPlugin? Here is the code for my ...

Implementing Google AdWords Conversion Tracking code on a button click event using knockoutjs

I recently received the following code snippet from Google AdWords for tracking purposes. <script type="text/javascript"> /* <![CDATA[ */ var google_conversion_id = 973348620; var google_conversion_language = "en"; var ...

The location of the THREE.Group object is consistently set at the origin (0, 0, 0) and errors may arise when attempting to accurately determine its position

In my Three.js project, I am utilizing a THREE.Group to manage selected dominoes within the scene. However, I am facing an issue where the reported position of the THREE.Group remains constant at (0, 0, 0) despite adding or removing objects to it. Addition ...

Display a standard chart using the Chart.js library, along with customizable options

I have successfully generated charts from a database using JSON script. However, I am facing an issue where the chart only displays when I click on an option value. What I want to achieve now is setting a default value option so that when the website ope ...

Countdown alert using JavaScript

Currently in my frontend code, I am utilizing angularjs as the javascript framework. In a specific section of my code, I need to display an error message followed by a warning message in this format: If a user inputs an incorrect month, then the following ...

Utilizing a raycasting technique in conjunction with the camera to achieve a dynamic crosshair effect reminiscent of Google Cardboard

I'm looking for a way to implement the Google Cardboard crosshair effect in my three.js scene. Essentially, I want to create a dot or crosshair in the center of the screen for VR navigation. How can I achieve this and use a raycaster to interact with ...

Customers will refresh themselves whenever the supplier refreshes

After reading through the React documentation, it explains that re-rendering all consumers occurs each time the Provider is re-rendered due to a new object being created for value. To see this in action, I decided to create a simple example: class App ...

Modifying HTML input value dynamically using JavaScript does not trigger the onchange event

Within my HTML code, I have an input field that is included in a form. Here is the input field snippet: <input type="text" name="group[{$sConfigurator.groupID}]" value="{$optionTopOptionID}" id="{$formSelectID}" onChange="this.form.submit();"/> A j ...

The print preview is unable to display all of the barcode images

Currently, I am utilizing the Jqprint plugin for printing purposes. Here is the code snippet for printing a barcode: HTML Code: <div class="wrapper_template" id="print_template"> <div class="imageOutput" > // Insert Barcode Printing Code ...

Issues with logging functionality in my React Native application

I am currently facing an issue with my React Native app running on the Android Studio emulator. The logging does not appear in my terminal or in the active remote debugger in Chrome when debugging is enabled. When I attempt to log a simple text in one of m ...

Can anyone provide guidance on uploading data to a mongodb database? I've attempted a few methods but keep encountering errors

const info = { name, price, quantity, image, desc, sup_name, email } fetch('https://gentle-plateau-90897.herokuapp.com/fruits', { method: 'POST', headers: { 'content-type': 'application/jso ...