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

qqrboqgw  于 2022-12-16  发布在  Electron
关注(0)|答案(1)|浏览(196)

x一个月一次x一个月一次x一个月一次x一个月二次x一个月三次x一个月四次x一个月五次x一个月六次x一个月七次x

  • 一个八个一x一个九个一x一个十个一x一个十个一x一个十个一x一个十个一x一个十个一x *

主文件. 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(索引. 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);})
x1米20英寸1x

呈现HTML(索引. html)

vbkedwbf

vbkedwbf1#

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

ipcRenderer.on("returnResponse",(event,text) => {
console.log(text);
})

相关问题