【问题标题】:How to run an electron app with arguments?如何运行带参数的电子应用程序?
【发布时间】:2017-01-13 21:53:15
【问题描述】:

我的应用是 electron,带有 BrowserWindow 加载本地页面 index.html。
我调用 npm run start 一个脚本来运行 electron main.js ,应用程序打开并加载了 html。
我可以在脚本中添加一个参数,将不同的 html 文件加载到 BrowserWindow 中吗?

main.js 文件中的代码是:

function createWindow () {
  // Create the browser window.
  mainWindow = new BrowserWindow({
    webPreferences:{
      webSecurity:false
    },
    fullscreen : false });//, alwaysOnTop : true , kiosk : true })
  mainWindow.setMenu(null);
  // and load the index.html of the app.
  let url = `file://${__dirname}/index.html`; \\ index.html should be determined by argument passed at start.  
  mainWindow.loadURL(url,loadOptions);

  // Open the DevTools.
  mainWindow.webContents.openDevTools();

  // Emitted when the window is closed.
  mainWindow.on('closed', function () {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    mainWindow = null;
  });
}

【问题讨论】:

  • process.argv 没有填充吗?
  • 是的,但是如何传递我的参数,例如 -html=index2.html

标签: node.js npm electron


【解决方案1】:

将命令行参数传递给电子应用程序:

./node_modules/.bin/electron main.js --arg1=value --arg2=value

在ma​​in.js中可以这样检索:

import { app } from "electron";
app.commandLine.getSwitchValue("arg1");
app.commandLine.getSwitchValue("arg2");

【讨论】:

    【解决方案2】:

    卸载显示名称

    这使您可以在 添加/删除程序控制面板小程序。该值可能包括 常数。如果此指令未指定或为空,安装程序将 使用 [Setup] 部分指令 AppVerName 的值作为名称。

    "build": {
      "nsis": {
        "uninstallDisplayName": "Your app name..."
      }
    }
    

    阅读更多:

    NSIS

    UninstallDisplayName

    【讨论】:

      【解决方案3】:

      传递参数的方式是一样的,你唯一需要注意的是电子路径。在package.json 中写入的npm start 将执行electron main.js。因此,您必须显式执行此命令并使用“正确的电子路径”传递参数,即./node_modules/.bin/electron。然后命令将是

      ./node_modules/.bin/electron main.js argv1 argv2
      

      您可以通过process.argv 在main.js 中访问这些参数

      如果您希望在您的应用程序中访问这些参数,则需要执行以下操作:

      1.在你的 main.js 中定义一个变量,如

           global.sharedObject = {prop1: process.argv}
      

      2.在您的应用中只需包含远程并使用此sharedObject

          var remote = require('electron').remote,
            arguments = remote.getGlobal('sharedObject').prop1;
      
          console.log(arguments);
      

      3.输出将是["argv1", "argv2"]

      来源:https://discuss.atom.io/t/how-to-pass-command-arguments-in-electron/17247

      【讨论】:

      • 对于一些为此苦苦挣扎的人,不要忘记在控制台中设置:> set ELECTRON_ENABLE_LOGGING=true
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多