LoginSignup
47
53

More than 5 years have passed since last update.

Electronでよく使いそうなネタの覚え書き

Last updated at Posted at 2016-09-25

jQueryを使う

jQueryはおそらく'module'あたりの名前がかち合っているため使用できない。
どうしても使いたい場合は、BrowserWindowのオプションでnodeItegration:false
を指定する。

こんな感じ
win = new BrowserWindow({
    webPreferences: {
        nodeIntegration: false,
    }
});

というか、zepto.jsのような互換ライブラリを使った方が楽。

複数インスタンス起動を禁止する

app.makeSingleInstanceでできる。

リンクをデフォルトブラウザで開く

webContents.new-windowイベントを引っかけてURLを取得し、shell.openExternal()で開く

メインプロセス内のコード
    mainWindow.webContents.on('new-window', (ev,url)=> {
        shell.openExternal(url);
    });

コンテキストメニューを開く

contextmenuイベントのリスナーで、メインプロセスのMenu.popup()を使用して開く

コンテキストメニューでカット、コピー、ペースト

カット、コピー、ペーストは専用のMenuItem.roleが用意されているので、それを使うだけ。

index.html
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <script src="../zepto.min.js"></script>
</head>
<body>
   てすと
    <script>
        const {Menu, MenuItem} = require('electron').remote;
        $('body').on('contextmenu', ev=> {
            ev.preventDefault();
            let menu = Menu.buildFromTemplate([
                {role:'copy'},
                {role:'cut'},
                {role:'paste'},
            ]);
            menu.popup();
            return false;
        });
    </script>
</body>
</html>

名前を付けて保存

webContents.downloadURL()だけで、保存先を選択するダイアログ表示→保存までできる。楽。

sample
    mainWindow.webContents.downloadURL(URL);

モーダルウィンドウ、モーダルダイアログ

BrowserWindowのオプションparentmodalを指定する。
ダイアログの場合は第1パラメータに親ウィンドウのBrowserWindowオブジェクトを指定する。

モーダルなウィンドウ/ダイアログは、これらを閉じるまで親ウィンドウの操作はできない。

モーダルウィンドウ
    const subWindow = new BrowserWindow({
        parent: mainWindow,     //親ウィンドウのBrowserWindowオブジェクト
        modal: true,
    });
    subWindow.loadURL(`file://${__dirname}/subwindow_content.html`);
モーダルダイアログ
    dialog.showMessageBox(mainWindow, {
        type: 'info',
        message: 'モーダルダイアログのテストですよ',
    });

フォーカスを奪わないウィンドウを開く

window.show()ではなくwindow.showInactive()で開くだけ。

    const subWindow = new BrowserWindow({
        parent: mainWindow, 
        show: false,
    });
    subWindow.loadURL(`file://${__dirname}/subwindow_content.html`);
    subWindow.showInactive();

ダイアログのボタン

dialog.showMessageBox()buttonsオプションでボタン名を指定しても、'ok' 'yes' 'no'等はボタンで表示されるが、それ以外はリンクで表示されてしまう。

    dialog.showMessageBox(mainWindow, {
        type: 'info',
        message: 'ダイアログのテストですよ',
        buttons: ['OK', 'yes', 'no', 'リンク?'],
    });

SnapCrab_electron_test_2017-4-18_22-46-27_No-00.png

全部ボタンにしたいときはnoLink: trueオプションを追加する。

    dialog.showMessageBox(mainWindow, {
        type: 'info',
        message: 'noLink:true',
        buttons: ['OK', 'yes', 'no', 'ボタン'],
        noLink: true,
    });

SnapCrab_electron_test_2017-4-18_22-46-14_No-00.png

47
53
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
47
53