【问题标题】:How to use electron ipc to update text field如何使用电子 ipc 更新文本字段
【发布时间】:2021-07-20 05:05:44
【问题描述】:

我一直在研究我的问题,所有箭头都指向 ipcRender / ipcMain 以在使用电子时处理 DOM 事件。但似乎在使用ipc时,网页进行发送,js文件进行接收。我需要倒着做——我不确定这是否准确或可能。所以我正在寻求一些澄清和帮助。

我的main.js 通过 ZMQ 连接到速率表并轮询位置和速度。我想反过来将收到的信息发送到我的index.html 并显示在文本字段中。此应用程序中的用户交互为零。 JS 代码只是运行并更新 HTML 前端中的值。 数据是从 pollPospollVel 函数收集和发送的 - 你会看到 ipcMain.send 是的,我知道这不是真正的功能。我不想等待事件发送,因为表中的数据更新非常快。

如何正确使用 ipc 将我的数据显示到文本字段中?还是我应该完全使用其他东西?

main.js

let zmq = require("zeromq");
const { stringify } = require("querystring");

// Electron stuff for the POSITION and VELOCITY GUI. 
const electron = require('electron');
const { app, ipcMain, BrowserWindow } = require('electron');
const path = require('path');
const { DH_NOT_SUITABLE_GENERATOR } = require("constants");
const { deflate } = require("zlib");

// function for delay 
const delay = ms => new Promise(res => setTimeout(res, ms));

// creating ZMQ Request
let sock = new zmq.Request();

// Bool for connection to Rate Table. 
let connected = Boolean(false);

// Events for the zmq request.
let events = sock.events;

// Global instance of guiWindow. 
var guiWindow;

// When the app is ready, create window and attempt table connection
app.on('ready', () => {
    try{
        // Create window for gui - will not show until connection is successfully established.
        createWindow();
        // Connect to the table
        connectTable();
    }catch(e){
        // Catch connection error
        console.log(e);
    }
});

// Event for connection
events.on("connect", async () => {
    // notify connected, set bool. 
    console.log("Connected.");
    connected = true;

    // show the gui 
    guiWindow.show();

    // while connected, poll for position and velocity.
    while(connected === true){
        await pollPos();
        await pollVel(); 
    } 
});

// -------------------------------------------------------------------------------------------------------
// createWindow - Creates the electron window for the HTML. 
// -------------------------------------------------------------------------------------------------------
function createWindow () {
    guiWindow = new BrowserWindow({
      show: false,
      titleBarStyle: 'hidden',
      autoHideMenuBar: true,
      width: 400,
      height: 320,
      resizable: false,
      frame: true,
      webPreferences: {
        nodeIntegration: true
      }
    });
  
    guiWindow.loadFile('index.html');
  }

// -------------------------------------------------------------------------------------------------------
// connectTable - essentially the main function - while the application is not connected, it repeatedly
//              attemps to connect. 
// -------------------------------------------------------------------------------------------------------
let connectTable = async () => {

    var attemptCount = 0; 
    while(!connected) {
        console.log("Connecting...");
        attemptCount++;
        await sock.connect("tcp://169.254.114.186:1250");
        await new Promise((resolve,reject)=>{setTimeout(resolve,1000);});
        await delay(1500); // wait 1.5s before attempting to connect again. 

        // Throw error after 15 unsuccessful attempts. 
        if(attemptCount > 15){
            throw "\n\n--Max Connection Attempts Exceded--\nPlease check cables and verify rate table is turned on.\nThen restart application.\n";
        }
    }
    
    return;
};

// // -------------------------------------------------------------------------------------------------------
// pollPos - polls table for position
// -------------------------------------------------------------------------------------------------------
let pollPos = async () => {
    let logic = new Promise((resolve, reject) => {
            // Send the command and wait for the response.
            sock.send("PPO").then(async (result) => {
                let [pMSG] = await sock.receive();
                console.log(" position: " + pMSG.toString('utf8'));
                ipcMain.send('updatePos',pMSG.toString('utf8'));
                return resolve(result);
            }, (error) => {
                console.error(error);
            });
    });
    return logic;
};

// -------------------------------------------------------------------------------------------------------
// pollVel - polls table for velocity
// -------------------------------------------------------------------------------------------------------
let pollVel = async () => {
    let logic = new Promise((resolve, reject) => {
            // Send the command and wait for the response.
            sock.send("PVE").then(async (result) => {
                let [vMSG] = await sock.receive();
                console.log(" velocity: " + vMSG.toString('utf8'));
                ipcMain.send('updateVel',vMSG.toString('utf8'));
                return resolve(result);
            }, (error) => {
                console.error(error);
            });
    });
    return logic;
};

index.html

<!DOCTYPE html>
<script>
    const { ipcRenderer } = require('electron')

    ipcRenderer.on('updatePos', (event, message) => {
        document.getElementById('pField').innerHTML = message
    });
    ipcRenderer.on('updateVel', (event, message) => {
        document.getElementById('vField').innerHTML = message
    });
</script>
<html>
<head>
    <meta charset="UTF-8">
    <title>Position/Velocity GUI</title>
    <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />
</head>
<style>
    input[type=text]{
        width: 60%;
        border: 2px solid #aaa;
        border-radius: 4px;
        margin: 8px 0;
        outline: none;
        padding: 15px;
        box-sizing: border-box;
        font-size: 18px;
        text-align: right;
    }
</style>
<body style="background: white;">
    <p>
        <h2>Position:</h2>
        <input type="text" id="pField" placeholder="0.000" readonly>
        <h2>Velocity:</h2>
        <input type="text" id="vField" placeholder="0.000" readonly>
    </p>
</body>
</html>

【问题讨论】:

    标签: html node.js electron


    【解决方案1】:

    简单的改变:

    ipcMain.send('updatePos',pMSG.toString('utf8'));
    ipcMain.send('updateVel',vMSG.toString('utf8'));
    

    收件人:

    guiWindow.webContents.send('updatePos',pMSG.toString('utf8'));
    guiWindow.webContents.send('updateVel',vMSG.toString('utf8'));
    

    据我所知,IPC 应该能够处理快速请求,所以试一试,看看结果如何。

    See docs:

    也可以从主进程向渲染进程发送消息,更多信息请参见webContents.send

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-11-17
      • 2019-02-26
      • 2015-04-12
      • 2023-02-21
      • 2020-08-17
      • 2018-06-07
      • 1970-01-01
      相关资源
      最近更新 更多