| ページ一覧 | ブログ | twitter |  書式 | 書式(表) |

MyMemoWiki

Electron

提供: MyMemoWiki
2021年9月25日 (土) 23:31時点におけるPiroto (トーク | 投稿記録)による版 (→‎app)
ナビゲーションに移動 検索に移動

| Node.js | JavaScript | TypeScript | npm | Flutter |

目次

Electron

Fiddle


API Document


Required

基本的なアプリの作成


  • Electronアプリケーションは本質的にNode.jsアプリケーション
  • Electronアプリケーションは、package.json から開始される

プロジェクトの作成とElectronのインストール

  1. mkdir my-electron-app && cd my-electron-app
  2. npm init -y
  3. npm i --save-dev electron
  • グローバルにインストール

npm

  1. npm -g i electron

mainスクリプトファイル(main.js)の作成


  • mainスクリプトは、Electronアプリケーションのエントリーポイント
  • Mainプロセスを開始し、Mainプロセスはアプリケーションのライフサイクルをコントロールする
  1. const { app, BrowserWindow } = require('electron')
  2. const path = require('path')
  3.  
  4. function createWindow() {
  5. const win = new BrowserWindow({
  6. width:400,
  7. height:300,
  8. webPreferences:{
  9. preload: path.join(__dirname, 'preload.js')
  10. }
  11. })
  12. win.loadFile('index.html')
  13. }
  14.  
  15. app.whenReady().then(() => {
  16. createWindow()
  17.  
  18. app.on('activate', () =>{
  19. if (BrowserWindow.getAllWindows().length == 0) {
  20. createWindow()
  21. }
  22. })
  23. })
  24.  
  25. app.on('window-all-closed', () => {
  26. if (process.platform !== 'darwin') {
  27. app.quit()
  28. }
  29. })

Webページ(index.html)の作成


  • index.html
  • アプリケーション初期化時に一度だけ表示されるページ
  • このページがレンダープロセスを表現する
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta carhset="UTF-8">
  5. <title>Electron Sample</title>
  6. <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />
  7. </head>
  8. <body style="background: white;">
  9. <h2>Version</h2>
  10. <div>
  11. We are using Node.js <span id="node-version"></span>
  12. </div>
  13. <div>
  14. Chromium <span id="chrome-version"></span>,
  15. </div>
  16. <div>
  17. Electron <span id="electron-version"></span>.
  18. </div>
  19. </body>
  20. </html>

プレロードスクリプト(preload.js)


  • Node.jsとWebページのブリッジ
  • Node.js全体を安全に公開するのではなく、特定のAPIや動作をWebページに公開することができる
  • 以下ではprocessオブジェクトからバージョン情報を読み取りページを更新する
  1. window.addEventListener('DOMContentLoaded', () => {
  2. const replaceText = (selector, text) => {
  3. const element = document.getElementById(selector);
  4. if (element) {
  5. element.innerText = text;
  6. }
  7. }
  8. for (const type of ['chrome', 'node', 'electron']) {
  9. replaceText(`${type}-version`, process.versions[type])
  10. }
  11. })

package.json


  1. {
  2. "name": "electron_sample",
  3. "version": "1.0.0",
  4. "main": "main.js",
  5. "scripts": {
  6. "start": "electron .",
  7. },
  8. :
  9. }

.gitignore


起動


  1. npm start

Electron sample start.png

Visual Studio Codeでのデバッグ


launch.json Node を Visual Studio Code でデバッグするときにグローバルにインストールしたモジュールが読み込まれない

  1. {
  2. "version": "0.2.0",
  3. "configurations": [
  4. {
  5. "name": "Debug Main Process",
  6. "type": "node",
  7. "request": "launch",
  8. "cwd": "${workspaceFolder}",
  9. "runtimeExecutable": "${workspaceFolder}/node_modules/.bin/electron",
  10. "windows": {
  11. "runtimeExecutable": "${workspaceFolder}/node_modules/.bin/electron.cmd"
  12. },
  13. "args" : ["."],
  14. "outputCapture": "std"
  15. }
  16. ]
  17. }

パッケージングと配布


Electron Forge


  • もっともシンプルで素早く配布するには、Electron Forgeを利用する
Electron ForgeをアプリケーションフォルダにImport
  1. $ npm install --save-dev @electron-forge/cl
  2. $ npx electron-forge import
  3. Checking your system
  4. Initializing Git Repository
  5. Writing modified package.json file
  6. Installing dependencies
  7. Writing modified package.json file
  8. Fixing .gitignore
  9.  
  10.  
  11. We have ATTEMPTED to convert your app to be in a format that electron-forge understands.
  12.  
  13. Thanks for using "electron-forge"!!!
Mac 配布パッケージを作成

  • out フォルダに出力される
  1. $ npm run make
  2.  
  3. > fx_sample@1.0.0 make
  4. > electron-forge make
  5.  
  6. Checking your system
  7. Resolving Forge Config
  8. We need to package your application before we can make it
  9. Preparing to Package Application for arch: x64
  10. Preparing native dependencies
  11. Packaging Application
  12. Making for the following targets: zip
  13. Making for target: zip - On platform: darwin - For arch: x64

Electron forge mac.png

Windows配布パッケージの作成


  • MacWindows用のパッケージ出力には、monoなどインストールが必要なようなので、Windows同様の手順でパッケージを作成。

Electron forge win.png

Ubuntu配布パッケージの作成


  1. $ sudo apt install dpkg-dev
  2. $ sudo apt install rpm
$ npm run make

Electron forge ubuntu.png

Electronの知識

プロセス


メインプロセスとレンダラープロセス


  • main.js がメインプロセスを担い、GUIは持たない
  • レンダーラープロセスは、Electronに内臓のWebブラウザを利用する
    • Electronの機能を利用する場合、、electron.remote経由

IPC(プロセス間通信)


  • メインプロセスとレンダラープロセスで情報を授受する場合、IPCを利用する
  • ページAからページBを操作したい場合など、メッセージを ページA->メインプロセス->ページBと連携させる必要がある

構成

mainn.js


const { app, BrowserWindow} = require('electron');

function createWindow() {
    let win = new BrowserWindow({
        width: 400,
        height: 200,
        webPreference: {
            nodeIntegration: true
        }
    });
    win.loadFile('index.html');
}

app.whenReady().then(createWindow);

オブジェクトの分割代入

const { app, BrowserWindow} = require('electron');

Node.js機能の統合

  • trueでNode.jsの機能を利用できるようになる
nodeIntegration: true

オブジェクト

app


  • アプリケーション本体
  • 起動/終了、Windowオープン/クローズなどの管理

BrowserWindow


  • Electronアプリで表示されるウィンドウオブジェクト
  • HTMLファイルを読み込むことでウィンドウを表示する

WebContents


  • BrowserWindowに含まれ、Webコンテンツの状態管理
  • Webコンテンツに関するイベント

Webページをロード


  • loadURLとすることで、外部ページをロードできる
   // win.loadFile('index.html');
   win.loadURL('https://service.typea.info/blogwiki');
 

Electron web app.png

モーダルダイアログ


function createWindow() {
    let win = new BrowserWindow({
        width: 600,
        height: 400,
        webPreference: {
            nodeIntegration: true
        }
    });
    // win.loadURL('https://service.typea.info/blogwiki');
    win.loadFile('index.html');

    let child = new BrowserWindow({
        width: 400,
        height: 200,
        parent: win,
        frame: false,
        modal: true,
        transparent: true,
        opacity: 0.5
    });
    child.loadFile('dialog.html');
}

Electron modal dialog.png

デベロッパーツールを開く


win.webContents.openDevTools();

Electron devtools.png

appオブジェクトのイベント

起動処理の完了

will-finish-launching

初期化処理完了

ready

BrowserWindowの生成

browser-window-created

Webコンテンツの生成

web-contents-created

全てのWindowが閉じられた

window-all-closed

全てのWindowを閉じる前

before-quit

終了する前

will-quit

終了時

quit

BrowserWindowのイベント

Windowの表示

show

Windowの非表示

hide

Window表示準備完了

ready-to-show

Windowを閉じる

close

Windowが閉じられた

closed

その他

  • focus
  • blur
  • maximize
  • unmaximize
  • minimize
  • restore
  • will-resize
  • resize
  • will-move
  • move
  • enter-full-screen
  • leave-full-screen
  • enter-html-full-screen
  • leave-html-full-screen
  • always-on-top-changed

BrowseWindow操作

  • destory
  • close()
  • focus()
  • blur()
  • isFocuced()
  • isDestoryed()
  • show()
  • showInactive()
  • hide()
  • isVisible()
  • isModal()
  • maximize()
  • unmaximize()
  • isMaximized()
  • minimize()
  • restore
  • isMinimized()
  • setFullScreen()
  • isFullScreen()
  • isNormal()
  • SetBounds()
  • GetBounds()
  • SetContentBounds()
  • GetContentsBound()
  • SetSize()
  • GetSize()
  • SetContaentSize()
  • GetContentSize()
  • SetMinimumSize()
  • GetMinimumSize
  • SetMaximumSize()
  • GetMaximumSize()
  • SetPosition()
  • GetPosition()
  • moveTop()
  • center()
  • settitle()
  • getTitle()

WebContentsのイベント

コンテンツロード完了

did-finish-load

フレームのコンテンツロード

did-frame-finish-load

コンテンツ読み込み開始

did-start-loading

コンテンツ読み込み中止

did-stop-loading

DOM生成完了

dom-ready

新しいWindow作成

new-window

URLアクセス時

will-navigate

URLアクセス開始

did-start-navigation

その他

  • will-redirect
  • did-redirect-navigation
  • did-navigate
  • will-prevent-unload
  • destroyed
  • enter-html-full-screen
  • leave-html-full-screen
  • zoom-changed
  • devtools-opend
  • devtools-closed
  • devtools-focused
  • console-message