4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ElectronのRenderProcessで、コマンドライン引数を取得する方法

Last updated at Posted at 2016-07-02

前回から引き続き画像ビューワーを作るための技術調査の続きです。
画像ビュワーを作成するためには、画像ファイル、フォルダ、圧縮ファイルを受け取る必要があります。
要素技術の一つとして、コマンドライン引数の取得方法を調べてみました。
electronはベースとなる技術が、nodeのためprocess.argvから取得できます。
ただし、RenderProcessで利用するためには、プロセス間通信を使って、MainProcessから取得する必要があります。

main.js
'use strict';
var app = require('app');
var BrowserWindow = require('browser-window');
var mainWindow = null;

require('crash-reporter').start();

app.on('window-all-closed', function () {
    if (process.platform != 'darwin') {
      app.quit();
    }
});
app.on('ready', function () {
    mainWindow = new BrowserWindow({width: 800, height: 600});
    mainWindow.loadURL('file://' + __dirname + '/index.html');
    mainWindow.on('closed', function() {
        mainWindow = null;
    });
});

remoteオブジェクトを利用して、remote.process.argvと指定します。

index.html
<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>electron command line argv get sample</title>
</head>

<body>
    <h1>コマンドライン引数</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>.
    <div><ul id="container"></ul></div>
    <script>
        // node_integrationを行うとmodule.exports関係の事情でjQuery/$がundefinedになるので
        // それの回避コード
        window.jQuery = window.$ = require('./js/jquery-3.0.0.min.js');
    </script>
    <script>
        var remote = require('remote');
        var argv = remote.process.argv;
        var container = document.getElementById('container');

        for(var i = 0; i < argv.length; i++)
        {
            var li = document.createElement('li');
            var tnode = document.createTextNode(argv[i]);

            li.appendChild(tnode);
            container.appendChild(li);
        }
    </script>
</body>

</html>

引数の2つ目からが指定されたファイル(フォルダ)として利用できます。

image

ソースコードは、Githubに置いてあります。

では、Nautilus(Windowsで言えばファイルエクスプローラー)からどのように、呼び出すのでしょうか?
1つは、debパッケージを作成して、ソフトウェアセンターからインストールする方法が正攻法なのですが、筆者の技量では、まだ無理でした。(涙)
正攻法は、後々攻略するとして、もうひとつの方法。右クリックメニュー(コンテクストメニュー)をカスタマイズする方法を試しました。
右クリックメニューをカスタマイズするツール(Nautilus-Actions Configuration Tool)をインストールします。

image

インストールしたら再起動をして、ツールを有効にしてからカスタムメニューを設定します。
自作Electronアプリのパスとパラメーターに、%Fを指定すれば、コマンドライン引数としてファイル名が指定されてきます。

image

image

image

なんとか、思ったような動きをしてくれるようです。

4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?