首页 > 解决方案 > 运行“First Electron App”不会显示版本?

问题描述

我正在关注Electron 快速入门指南,它可以正常工作,但输出与文档中描述的不同,document.write输出中不会显示带有的版本。

这是我的输出:

Hello World!

We are using node , Chrome , and Electron .

我的预期输出将包括相应的版本号。

我检查了应用程序的 GitHub 页面,仍然一样,尝试了各种 StackOverflow 答案,但没有一个对我有用。

索引.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello World!</title>
</head>
<body>
<h1>Hello World!</h1>
We are using node <script>document.write(process.versions.node) </script>,
Chrome <script>document.write(process.versions.chrome)</script>,
and Electron <script>document.write(process.versions.electron) </script>.
</body>
</html>

包.json

{
    "name": "electronapp",
    "version": "1.0.0",
    "description": "",
    "main": "main.js",
    "scripts": {
       "start": "electron ."
    },
    "author": "harsh",
    "license": "ISC",
    "devDependencies": {
        "electron": "^5.0.2"
    }
}

main.js

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

function createWindow () {
    mainWindow = new BrowserWindow({
        width: 800,
        height: 600,
        webPreferences: {
            preload: path.join(__dirname, 'preload.js')
        }
    })

    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()
})

我已经全局安装了 Node,并且 Chrome 与 Electron 一起打包,对吧?

标签: node.jselectron

解决方案


如果您激活开发者工具,您应该会在控制台中看到如下错误消息:

Uncaught ReferenceError: process is not defined
    at index.html:11

您需要激活nodeIntegration和停用BrowserWindow,以便允许在 BrowserWindow 中运行的进程(“渲染器进程”)访问 Node 的contextIsolation对象。process

mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
        nodeIntegration: true,
        contextIsolation: false
    }
})

(在 Electron 12 之前,只nodeIntegration需要 key,默认值为。contextIsolationfalse


推荐阅读