如何从 Electron js 应用程序中的 main.js 获取 renderer.js 中的块数据

问题描述 投票:0回答:1

我必须从我的电子应用程序中的服务器获取数据,我正在使用节点js的“net”模块。 由于“net”是主进程模块,我无法直接从渲染器文件访问它。 我必须在 main.js 文件中使用“net”模块。 我按照tutorial中的两种方式IPC进行操作。 通过这种方法,我设法从 main.js 文件中的服务器获取数据,因为我可以在控制台日志中打印。但是当我尝试将此数据返回给渲染器时,它不起作用。 在渲染器上收到以下消息

Promise {<pending>}
[[Prototype]]: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: undefined

main.js

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

const path = require("path");
const remoteMain = require('@electron/remote/main');
remoteMain.initialize();

let text;
let win;

function handleData() {
    const request = net.request({
        method: 'GET',
        protocol: 'http:',
        hostname: 'some IP address',
        port: some port,
        path: '/some path',
        redirect: 'follow'
    });
    request.on('response', (response) => {
        console.log(`STATUS: ${response.statusCode}`)
        console.log(`HEADERS: ${JSON.stringify(response.headers)}`)
        response.on('data', (chunk) => {
            // console.log(`${chunk}`)
            text = `${chunk}`;
            console.log(text); // this prints the json data on console.
            / tried  return text; but same error.
        })
        response.on('end', () => {
            console.log('No more data in response.')
            console.log(text); // this prints the json data on console.
            return text;
        })
    })
    request.end()
};

const createWindow = () => {
    win = new BrowserWindow({
        width: 800,
        height: 600,
        webPreferences: {
            preload: path.join(__dirname, 'preload.js'),
        },
    })
    remoteMain.enable(win.webContents)
}

function openIndex() {
    win.loadFile('HTML/index.html');
    win.webContents.openDevTools();
}

ipcMain.handle("request:get", handleData);

app.whenReady().then(() => {
    createWindow();
    openIndex();
    app.on("activate", function() {
        if (BrowserWindow.getAllWindows().length === 0) createWindow();
    });
});

app.on("window-all-closed", function() {
    if (process.platform !== "darwin") app.quit();
});

预加载.js

const { contextBridge, ipcRenderer } = require("electron");
contextBridge.exposeInMainWorld("electronAPI", {
  getData: () => ipcRenderer.invoke("request:get", message),
});

渲染器.js (index.js)

const btnclick = document.getElementById("PFLIoT");

btnclick.addEventListener("click", () => {
  console.log("Hello from Machine List IOT");

  const response = window.electronAPI.getData();

  console.log(response);

  // Also tried this code
  // window.electronAPI.getData().then((data) => {
  // console.log(data);})
});

渲染 HTML(index.html)

<html>
   <head>
      <link rel="stylesheet" href="../css/layout.css" >
   </head>
   <body>
      <div class="area"></div>
      <nav class="main-menu">
         <ul>
         <li>
            <a href="#">
            <i class="fa fa-home fa-2x"></i>
            <span class="nav-text">
            Dashboard
            </span>
            </a>
         </li>
         <li class="has-subnav">
            <a href="#home">
            <i class="fa fa-laptop fa-2x"></i>
            <span class="nav-text">
            </span>
            </a>
         </li>
      </nav>
   </body>
   <script src="../js/layout.js"> </script>
</html>
javascript electron ipc ipcrenderer
1个回答
1
投票

我终于得到答案了。 我只需在 preload.js 文件中再添加一行

ipcRenderer.on("returnResponse",(event,text) => {
console.log(text);
})
© www.soinside.com 2019 - 2024. All rights reserved.