简体   繁体   中英

Can't use event listeners in renderer process in electron

I'm trying to make an Electron app with an input, which value will be used for setting the app's progress bar via win.setProgressBar()

I tried to use ipc to send a message from the renderer process to the main process. I tried adding blur and click event listeners for the input, using a function defined above, but they don't seem to be applied correctly.

Renderer process :

const {ipcRenderer} = require("electron");

function setProgress(pgrss) {
    console.log("fromage"); // For debugging purposes
    ipcRenderer.send("sendMainMessage", {
        progress: pgrss
    });
};

document.getElementById("progress").addEventListener("click", setProgress(parseFloat(document.getElementById("progress").value)));

Input in HTML page :

<div class="pane">
    <input id="progress" type="number" value="0.5">
</div>

Loading the renderer JS in HTML page :

<script>
  require("electron-photon")
  require('./renderer.js')
</script>

Main process ipc receiver :

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

// ...

ipcMain.on("sendMainMessage", (event, properties) => {
  mainWindow.setProgressBar(properties.progress);
});

I except the app's progress bar to be set to the value I'm putting in the input field when the event on it happens, via the renderer process and ipc. According to devtools, it looks like the renderer process's function used for the event listener runs once at load, and the event listener isn't applied to the input field. Here's what shows in the console, doesn't depend on if something was typed in the input or not : https://i.imgur.com/poxXOY5.png . And in the Event Listener tab for the input element, no event listener shows from the renderer script.

I believe I found my answer here : Input addEventListener on change not firing . the problem is that I am passing the addEventListener function the result of the setProgress() function.

As said in the link, I'll try .bind or a function statement/arrow function when I'll have time.

I believe that the issue is that the event listener tries to attach before the DOM is fully loaded, leading to it attaching to nothing. You could load jquery into your project and use its default ready function to make sure the DOM exists before trying to attach a listener, or write something yourself. See: How to wait until an element exists? for further clarification.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM