electron app json 使用 ipc 渲染器的数据
electron app json data to renderer using ipc
我是电子新手,如果我的问题很幼稚,我很抱歉
但我已经将一些用户输入数据作为对象从渲染器发送到主存储在 json 文件(电子数据库)中
但我想在 table 中显示所有数据
我厌倦了 event.reply 但它只在预加载日志中给出了我想要的结果
我不知道如何将它从预加载到 html table
在这里我附上了来自 main
的代码
// catch obj This is Main.js
ipcMain.on("message", (event, obj) => {
db.createTable("medicine", (succ, msg) => {
// succ - boolean, tells if the call is successful
if (succ) {
console.log(msg);
} else {
console.log("An error has occured. " + msg);
}
});
console.warn(obj);
if ((db.valid("medicine"), location)) {
db.insertTableContent("medicine", obj, (succ, msg) => {
// succ - boolean, tells if the call is successful
console.log("Success: " + succ);
console.log("Message: " + msg);
});
}
let row;
const app = electron.app || electron.remote.app;
db.getAll("medicine", (succ, data) => {
// succ - boolean, tells if the call is successful
// data - array of objects that represents the rows.
// console.warn(data);
row = data;
});
console.warn(row)
event.reply("message", row)
});
这是我的预加载
const {contextBridge, ipcMain, ipcRenderer} = require('electron');
const API = {
sendmsg: (obj) => ipcRenderer.send("message", obj)
}
// const getAllData = function fetchData(){
// ipcRenderer.send("req", "this is requirment for All data")
// }
ipcRenderer.on("message", (_event, row) => {
console.log(row)
})
contextBridge.exposeInMainWorld("api", API);
consol.log(row)
为我的数据库中的所有数据提供一个数组
但我不知道如何在 html 文件脚本或渲染器
中使用它
您的 IPC 布线有点混乱。为了简化您的脚本,请尝试将它们分成各自的功能。 IE:使用你的 preload.js
脚本只允许主进程和渲染进程之间的通信。
不知道您使用的是什么数据库,我假设您的数据库代码是正确的并且可以正常工作。
下面是我如何 set-up 我的 preload.js
脚本并使用它在进程之间进行通信的示例。
此 preload.js
脚本使用列入白名单的通道名称来识别可以使用哪些 IPC 通信线路,类似于 Node.js eventName。
preload.js
(主进程)
// Import the necessary Electron components.
const contextBridge = require('electron').contextBridge;
const ipcRenderer = require('electron').ipcRenderer;
// White-listed channels.
const ipc = {
'render': {
// From render to main.
'send': [],
// From main to render.
'receive': [],
// From render to main and back again.
'sendReceive': [
'message' // Channel name
]
}
};
// Exposed protected methods in the render process.
contextBridge.exposeInMainWorld(
// Allowed 'ipcRenderer' methods.
'ipcRender', {
// From render to main.
send: (channel, args) => {
let validChannels = ipc.render.send;
if (validChannels.includes(channel)) {
ipcRenderer.send(channel, args);
}
},
// From main to render.
receive: (channel, listener) => {
let validChannels = ipc.render.receive;
if (validChannels.includes(channel)) {
// Deliberately strip event as it includes `sender`.
ipcRenderer.on(channel, (event, ...args) => listener(...args));
}
},
// From render to main and back again.
invoke: (channel, args) => {
let validChannels = ipc.render.sendReceive;
if (validChannels.includes(channel)) {
return ipcRenderer.invoke(channel, args);
}
}
}
);
为简洁起见,我已将您的数据库代码包含在下面的 main.js
文件中。
main.js
(主进程)
'use strict';
const electronApp = require('electron').app;
const electronBrowserWindow = require('electron').BrowserWindow;
const electronIpcMain = require('electron').ipcMain;
const nodePath = require("path");
// db = require('db'); // Your (connected) database
let window;
function createWindow() {
const window = new electronBrowserWindow({
x: 0,
y: 0,
width: 800,
height: 600,
show: false,
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
preload: nodePath.join(__dirname, 'preload.js')
}
});
window.loadFile('index.html')
.then(() => { window.show(); });
return window;
}
electronApp.on('ready', () => {
window = createWindow();
});
electronApp.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
electronApp.quit();
}
});
electronApp.on('activate', () => {
if (electronBrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
// ---
// From render to main and back again
electronIpcMain.handle('message', (event, obj) => {
// Create the table
db.createTable("medicine", (succ, msg) => {
if (succ) {
console.log(msg);
} else {
console.log('An error has occurred. ' + msg);
}
});
console.warn(obj);
// Insert your data object
if ((db.valid("medicine"), location)) {
db.insertTableContent("medicine", obj, (succ, msg) => {
console.log('Success: ' + succ);
console.log('Message: ' + msg);
});
}
let rows;
// Retrieve all rows
db.getAll("medicine", (succ, data) => {
// succ - boolean, tells if the call is successful
// data - array of objects that represents the rows.
// console.warn(data);
rows = data;
});
console.warn(rows);
return rows; // Simple return the result via IPC
// Testing purposes.
// let rows = [
// {"name": "Amoxicillin", "weight": "250mg"},
// {"name": "Codeine", "weight": "50mg"},
// {"name": "Penicillin", "weight": "25mg"}
// ];
//
// rows.push(obj);
//
// console.log(rows);
//
// return rows;
})
最后,我尝试实现您的 index.html
文件的基本功能。
index.html
(渲染过程)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Medicine</title>
</head>
<body>
<h1>Add Medicine</h1>
<label for="name">Name: </label>
<input id="name" type="text">
<label for="weight">Weight: </label>
<input id="weight" type="text">
<input id="button" type="button" value="Add">
</body>
<script>
let name = document.getElementById('name');
let weight = document.getElementById('weight');
document.getElementById('button').addEventListener('click', () => {
// From render to main and (.then) back again
window.ipcRender.invoke('message', {"name": name.value, "weight": weight.value})
.then((rows) => {
console.log(rows);
})
})
</script>
</html>
我是电子新手,如果我的问题很幼稚,我很抱歉 但我已经将一些用户输入数据作为对象从渲染器发送到主存储在 json 文件(电子数据库)中 但我想在 table 中显示所有数据 我厌倦了 event.reply 但它只在预加载日志中给出了我想要的结果 我不知道如何将它从预加载到 html table 在这里我附上了来自 main
的代码// catch obj This is Main.js
ipcMain.on("message", (event, obj) => {
db.createTable("medicine", (succ, msg) => {
// succ - boolean, tells if the call is successful
if (succ) {
console.log(msg);
} else {
console.log("An error has occured. " + msg);
}
});
console.warn(obj);
if ((db.valid("medicine"), location)) {
db.insertTableContent("medicine", obj, (succ, msg) => {
// succ - boolean, tells if the call is successful
console.log("Success: " + succ);
console.log("Message: " + msg);
});
}
let row;
const app = electron.app || electron.remote.app;
db.getAll("medicine", (succ, data) => {
// succ - boolean, tells if the call is successful
// data - array of objects that represents the rows.
// console.warn(data);
row = data;
});
console.warn(row)
event.reply("message", row)
});
这是我的预加载
const {contextBridge, ipcMain, ipcRenderer} = require('electron');
const API = {
sendmsg: (obj) => ipcRenderer.send("message", obj)
}
// const getAllData = function fetchData(){
// ipcRenderer.send("req", "this is requirment for All data")
// }
ipcRenderer.on("message", (_event, row) => {
console.log(row)
})
contextBridge.exposeInMainWorld("api", API);
consol.log(row)
为我的数据库中的所有数据提供一个数组
但我不知道如何在 html 文件脚本或渲染器
您的 IPC 布线有点混乱。为了简化您的脚本,请尝试将它们分成各自的功能。 IE:使用你的 preload.js
脚本只允许主进程和渲染进程之间的通信。
不知道您使用的是什么数据库,我假设您的数据库代码是正确的并且可以正常工作。
下面是我如何 set-up 我的 preload.js
脚本并使用它在进程之间进行通信的示例。
此 preload.js
脚本使用列入白名单的通道名称来识别可以使用哪些 IPC 通信线路,类似于 Node.js eventName。
preload.js
(主进程)
// Import the necessary Electron components.
const contextBridge = require('electron').contextBridge;
const ipcRenderer = require('electron').ipcRenderer;
// White-listed channels.
const ipc = {
'render': {
// From render to main.
'send': [],
// From main to render.
'receive': [],
// From render to main and back again.
'sendReceive': [
'message' // Channel name
]
}
};
// Exposed protected methods in the render process.
contextBridge.exposeInMainWorld(
// Allowed 'ipcRenderer' methods.
'ipcRender', {
// From render to main.
send: (channel, args) => {
let validChannels = ipc.render.send;
if (validChannels.includes(channel)) {
ipcRenderer.send(channel, args);
}
},
// From main to render.
receive: (channel, listener) => {
let validChannels = ipc.render.receive;
if (validChannels.includes(channel)) {
// Deliberately strip event as it includes `sender`.
ipcRenderer.on(channel, (event, ...args) => listener(...args));
}
},
// From render to main and back again.
invoke: (channel, args) => {
let validChannels = ipc.render.sendReceive;
if (validChannels.includes(channel)) {
return ipcRenderer.invoke(channel, args);
}
}
}
);
为简洁起见,我已将您的数据库代码包含在下面的 main.js
文件中。
main.js
(主进程)
'use strict';
const electronApp = require('electron').app;
const electronBrowserWindow = require('electron').BrowserWindow;
const electronIpcMain = require('electron').ipcMain;
const nodePath = require("path");
// db = require('db'); // Your (connected) database
let window;
function createWindow() {
const window = new electronBrowserWindow({
x: 0,
y: 0,
width: 800,
height: 600,
show: false,
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
preload: nodePath.join(__dirname, 'preload.js')
}
});
window.loadFile('index.html')
.then(() => { window.show(); });
return window;
}
electronApp.on('ready', () => {
window = createWindow();
});
electronApp.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
electronApp.quit();
}
});
electronApp.on('activate', () => {
if (electronBrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
// ---
// From render to main and back again
electronIpcMain.handle('message', (event, obj) => {
// Create the table
db.createTable("medicine", (succ, msg) => {
if (succ) {
console.log(msg);
} else {
console.log('An error has occurred. ' + msg);
}
});
console.warn(obj);
// Insert your data object
if ((db.valid("medicine"), location)) {
db.insertTableContent("medicine", obj, (succ, msg) => {
console.log('Success: ' + succ);
console.log('Message: ' + msg);
});
}
let rows;
// Retrieve all rows
db.getAll("medicine", (succ, data) => {
// succ - boolean, tells if the call is successful
// data - array of objects that represents the rows.
// console.warn(data);
rows = data;
});
console.warn(rows);
return rows; // Simple return the result via IPC
// Testing purposes.
// let rows = [
// {"name": "Amoxicillin", "weight": "250mg"},
// {"name": "Codeine", "weight": "50mg"},
// {"name": "Penicillin", "weight": "25mg"}
// ];
//
// rows.push(obj);
//
// console.log(rows);
//
// return rows;
})
最后,我尝试实现您的 index.html
文件的基本功能。
index.html
(渲染过程)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Medicine</title>
</head>
<body>
<h1>Add Medicine</h1>
<label for="name">Name: </label>
<input id="name" type="text">
<label for="weight">Weight: </label>
<input id="weight" type="text">
<input id="button" type="button" value="Add">
</body>
<script>
let name = document.getElementById('name');
let weight = document.getElementById('weight');
document.getElementById('button').addEventListener('click', () => {
// From render to main and (.then) back again
window.ipcRender.invoke('message', {"name": name.value, "weight": weight.value})
.then((rows) => {
console.log(rows);
})
})
</script>
</html>