Fri*_*erg 8 javascript forms node.js electron
我最近开始用Electron弄湿我的脚.我真的很喜欢它背后的原理,但我发现做一些事情有点令人困惑.
例如,您如何处理用户输入?我有一个main.js和一个指向本地html文件的BrowserWindow(包含一些带输入字段的用户设置).
提交HTML表单(同一个文件或另一个文件)时如何访问此数据?
main.js
const {app, BrowserWindow} = require('electron')
let win
function createWindow () {
win = new BrowserWindow({width: 800, height: 600})
win.loadURL('file://' + __dirname + '/index.html')
// Emitted when the window is closed.
win.on('closed', () => {
win = null
})
// Open the DevTools.
// win.webContents.openDevTools()
}
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', () => {
if (win === null) {
createWindow()
}
})
// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
//Start the main window
app.on('ready', createWindow)
Run Code Online (Sandbox Code Playgroud)
的index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<form action="" method="post">
<input type="text" name="test-1">
</form>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
使用 Electron,node.js 不像在典型的 Web 应用程序场景中那样充当具有路由的 Web 服务器。您可以使用 Angular、React、Knockout 等 javascript 框架创建单页应用程序,而不是向路由发送请求。此时,您不再需要处理路由。您可以将您的“提交”点击事件直接与页面内的 javascript 函数联系起来,并从那里处理输入。
您可以在页面的 javascript 上下文中执行所有操作,而在 node.js 主进程上下文中可以执行此操作。例如,如果您需要从您的页面访问文件系统,您可以使用Remote模块来访问 node.js 本机 API。
例如:
// Gain access to the node.js file system api
function useNodeApi() {
const remote = require('electron').remote;
const fs = remote.require('fs');
fs.writeFile('test.txt', 'Hello, I was written by the renderer process!');
}
Run Code Online (Sandbox Code Playgroud)
我很少遇到需要将控制权交还给主进程来完成某事的情况。一旦 BrowserWindow 启动,您可能需要做的任何事情都可以在渲染器进程中完成。这几乎消除了通过 http 提交表单帖子等操作的需要。
| 归档时间: |
|
| 查看次数: |
4052 次 |
| 最近记录: |