javascript - Electron - 处理输入

标签 javascript node.js forms electron

我最近开始接触 Electron。我真的很喜欢它背后的原则,但我发现做一些事情有点困惑。

例如,您如何处理用户输入?我有一个 main.js 和一个指向本地 html 文件的 BrowserWindow(包含一些带有输入字段的用户设置)。

当提交 HTML 表单时,我如何访问这些数据(到同一个文件或另一个文件)?

主要.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)

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>

最佳答案

有了 Electron,node.js 不像在典型的 Web 应用程序场景中那样充当具有路由的 Web 服务器。您可以使用 Angular、React、Knockout 等 javascript 框架创建单页应用程序,而不是向路由发送请求。此时,您不再需要处理路由。您可以将“提交”点击事件直接绑定(bind)到页面内的 javascript 函数,并从那里处理输入。

您可以从页面的 javascript 上下文中执行您可以从 node.js 主进程上下文中执行的所有操作。例如,如果您需要从您的页面访问文件系统,您可以使用 Remote模块以访问 node.js native 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!');
}

我很少遇到需要将控制权交还给主流程才能完成某事的情况。一旦 BrowserWindow 启动,您可能需要做的任何事情都可以从渲染器进程中完成。这几乎消除了通过 http 提交表单帖子等操作的需要。

关于javascript - Electron - 处理输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40306837/

相关文章:

javascript - 如何获取元素的类型。 JavaScript/jQuery

javascript - 奇怪的八进制行为

node.js - 当我运行 npm start 创建 React 应用程序时缺少脚本

html - 焦点时表单输入的图标消失

javascript - Bootstrap-Select打开div下的选项

javascript - Node : Cannot replace Intl to use IntlPolyfill

ios - 原生 IOS 应用和 node.js

angularjs - angularjs 中 !$pristine 与 $dirty 之间的区别是什么

php - 未执行自定义表单的 Silverstripe 3.1 操作

javascript - 通缉 : Minimal cross-browser Javascript library