首页 > 解决方案 > 将代码放在 Electron 应用程序中的什么位置以使 JavaScript 工作?

问题描述

我正在尝试将已写入电子应用程序的 JavaScript 获取。目前,我正在努力让任何事情发挥作用。

我希望按钮仅更改页面以显示日期。

这是在 HTML 中。

<button onclick="myne()">PRESS ME</button>

这是在index.js文件中。

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

function boot(){
win = new BrowserWindow()
win.setMenu(null);
win.loadURL(url.format({
    pathname: 'index.html',
    slashes: true
}))

function myne(){
document.write(date());
   }
}

我只是无法让 JavaScript 运行。我尝试将其用作外部文件以及尝试在引导功能之外编写该功能。

我也尝试过 require JS 的东西,但我认为我执行错了。

标签: javascriptelectron

解决方案


您可以按照以下示例进行操作:

main.js

const {app, BrowserWindow} = require('electron')
const path = require('path')
const url = require('url')

let mainWindow

function createWindow () {
  mainWindow = new BrowserWindow({width: 800, height: 600})
  mainWindow.loadFile('index.html')
  mainWindow.on('closed', function () {
    mainWindow = null
  })
}

app.on('ready', createWindow)

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

app.on('activate', function () {
  if (mainWindow === null) {
    createWindow()
  }
})

索引.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Hello World!</title>
  </head>
  <body>
    <button onclick="myne()">PRESS ME</button>
    <script>
      require('./renderer.js')
    </script>
  </body>
</html>

渲染器.js

window.myne = function() {
    document.write(new Date());
}

推荐阅读