ElectronでWebサービスをネイティブアプリっぽくしてみる

2019.10.25

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

こんにちは、CX事業本部の夏目です。

開発に使っている端末はMacなのですが、Alfredというツールを使ってアプリを切り替えるのが非常に便利です。

ただ、PWAに対応してないとWebサービスをアプリのように扱うことができません。
(自分は大量にタブを開いてしまう民なので、Webサービスを開いているタブを探すのが大変です)

そこで今回は、Electronを使ってWebサービスをネイティブアプリっぽくしてみようと思います。

Electron

クロスプラットフォームなアプリケーションを作るためのフレームワークです。
Chromiumが中に組み込まれていて、Webサービスを作るようにアプリケーションを作ることができます。

Electron | Build cross platform desktop apps with JavaScript, HTML, and CSS.

To get started with Electron, check out the resources below. Learn how to wrap your web app with Electron, access all the APIs, and generate installers. The Electron API Demos app interactively demonstrates the most important features of the Electron API. See what's possible with Electron with sample code and helpful tips for building your app.

AtomやVisual Studio Code、Slackのデスクトップアプリなどが有名ですね。

作ってみる

$ npm init -y
$ npm install --save-dev electron

まずは、Electronをインストールします。

次に、Electron起動時に呼ばれるJSファイルを作ります。

index.js

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

function createWindow () {
  // Create the browser window.
  let win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true
    }
  })

  win.loadURL('https://mimemo.io/')
}

app.on('ready', createWindow)

基本は公式ドキュメントに載っていたサンプルそのままです(ドキュメント)。
しかし、一箇所だけ変更して、 win.loadFilewin.loadURLに変更してます。
(ここでは、自分がMarkdownでメモをとるのに使ってるmimemoというサービスののURLを渡しています)

$ npx electron .

として、Electronを起動してみると、

動きました。

アプリとしてビルドする

次にビルドして、アプリを生成します。

Electronのビルドでは electron-builderが便利なそうなので、それを使っていきます。

$ npm install --save-dev electron-builder

ビルドするための設定はpackage.jsonに書くこともできるしJSファイルに書くこともできるようなので、JSファイルに書いていきます。

build.js

const builder = require('electron-builder');

builder.build({
    config: {
        'appId': 'electron.dummy.mimemo',
        'productName': 'mimemo'
    }
});

ビルド設定を書いたので、ビルドします。

$ node build.js
  • electron-builder  version=21.2.0 os=18.7.0
  • description is missed in the package.json  appPackageFile=/Users/natsume.yuta/workspace/nodejs/mimemo_electron/package.json
  • writing effective config  file=dist/builder-effective-config.yaml
  • packaging       platform=darwin arch=x64 electron=6.0.12 appOutDir=dist/mac
  • default Electron icon is used  reason=application icon is not set
  • skipped macOS application code signing  reason=cannot find valid "Developer ID Application" identity or custom non-Apple code signing certificate, see https://electron.build/code-signing allIdentities=

  • building        target=macOS zip arch=x64 file=dist/mimemo-1.0.0-mac.zip
  • building        target=DMG arch=x64 file=dist/mimemo-1.0.0.dmg
  • building block map  blockMapFile=dist/mimemo-1.0.0.dmg.blockmap
  • building embedded block map  file=dist/mimemo-1.0.0-mac.zip

$ find dist -depth 2
dist/mac/mimemo.app

アプリができました。

まとめ

PWAに対応していないWebサービスをネイティブアプリっぽくすることができました。

実はこれ、右クリックのメニューとか表示されないという欠陥はあるのですが、キーボードショートカットでコピペはできるので、メモをとる程度には使えそうです。