2
0

More than 3 years have passed since last update.

ElectronでMacOSのkeychainにアクセスしようとしてハマったこと

Last updated at Posted at 2020-05-11

仕事ではWebアプリケーションしか作らない私。
勉強をかねてElectronでデスクトップアプリ開発をしている中でどハマりした部分を記事にしておく。

やりたいこと

MacOSのkeychainにIDとパスワードを保存して手軽に再ログインできるようにしたい。
node-keytarを使用すれば簡単にできるとのこと
https://github.com/atom/node-keytar

やったこと

electron-react-boilerplateで開始
https://github.com/electron-react-boilerplate/electron-react-boilerplate

git clone --depth 1 --single-branch https://github.com/electron-react-boilerplate/electron-react-boilerplate.git kontamProject
cd kontamProject

とりあえずkeytarを導入してyarn install

yarn add keytar
yarn install

下記をapp/main.dev.tsの先頭に追加して雑に動作確認する

import keytar from 'keytar';
keytar.setPassword('kontamService', 'account', 'my-password');
keytar
  .getPassword('kontamService', 'account')
  .then(password => console.log('testing keytar', password));

keychainに適当な文字列を入れて、それを取り出してconsole出力できることを試したかった

で、とりあえず起動してみる

yarn dev

ハマったこと

そうするとこんなエラーが出る

App threw an error during load
Error: Module did not self-register.
    at process.func (electron/js2c/asar.js:140:31)
    at process.func [as dlopen] (electron/js2c/asar.js:140:31)
    at Object.Module._extensions..node (internal/modules/cjs/loader.js:922:18)
    at Object.func (electron/js2c/asar.js:140:31)
    at Object.func [as .node] (electron/js2c/asar.js:140:31)
    at Module.load (internal/modules/cjs/loader.js:735:32)
    at Module._load (internal/modules/cjs/loader.js:648:12)
    at Module._load (electron/js2c/asar.js:717:26)
    at Function.Module._load (electron/js2c/asar.js:717:26)
    at Module.require (internal/modules/cjs/loader.js:775:19)

Webやっててこんなエラーは見たことがない。
割と汎用的なエラーっぽくてググってもなかなかいい答えが見つからない

解決法

electron-rebuildによって解決する プロジェクトルートでinstall

yarn add electron-rebuild

そして実行

npx electron-rebuild

そうするとkeytarがリビルドされるようなメッセージが出るはず

そのあと実行

yarn dev

そうすると無事boilerplateのアプリが起動した。
コンソールには以下の出力があり、keytarが想定通り動いたことがわかる。

testing keytar my-password

結局何が問題だったのか

Electronのメインプロセス つまりNode.js上で動作するパッケージはElectronのバージョンに応じてリビルドする必要があるらしい。
electron-rebuildはそういったパッケージをまとめて1コマンドでリビルドしてくれるパッケージとのこと

なかなかググっても解決法が見つからずに長時間ハマったので、この記事が他の誰かの役に立つことを祈る

2
0
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
2
0