将命令行参数传递给电子可执行文件(在安装已打包的应用程序之后)

Passing command line arguments to electron executable (after installing an already packaged app)

我试图在执行时将命令行参数传递给我已经打包的应用程序。 (已经与 electron-builder 打包并在我的 mac 上安装了 .dmg)

我导航到应用程序可执行文件所在的 /Applications/myApp.app/Contents/MacOS 文件夹。然后我运行。 exec myApp --myNewArgument theFancyValue 由于某种原因 "myNewArgument" 没有出现在我的 process.argv 数组中。

我错过了什么吗?我以为争论会自动传递到我的电子主进程。

非常感谢您的帮助。

是的,传递的命令行参数出现在 process.argv 数组中,但仅来自 主进程

渲染器进程,您需要使用 remote.process:

访问主进程参数
require('electron').remote.process.argv

如果是电子应用程序的打包源,可以使用以下函数访问命令行参数。假设我们将命令行参数作为 --myNewArgument=theFancyValue 传递。可以在main.js:

中这样检索
import { app } from "electron";
app.commandLine.getSwitchValue("myNewArgument");

这也适用于开发模式。

https://www.electronjs.org/docs/api/command-line 表示

(commandLine.appendSwitch(...)) This will not affect process.argv. The intended usage of this function is to control Chromium's behavior.

因此,只有其他评论中提到的 appp.commandLine.getSwitchValue 允许您获得这些命令行开关

除了使用开关作为命令行参数外,还支持使用arguments。参数在最终命令行中采用“someData”的形式,其中开关采用“--namedParameter=someData”的形式。

在代码中,commandLine.appendArgument(value)用于添加参数。这些参数在生成的命令行中的所有开关之前给出。

它们还旨在影响 Chromium 的行为。再次:

(commandLine.appendArgument(value)) Note: This will not affect process.argv. The intended usage of this function is to control Chromium's behavior.

由于没有参数键,因此似乎无法像使用开关那样直接从代码中读取它。

https://www.electronjs.org/docs/api/command-line-switches 给出了支持的开关列表。