Electron + node.jsで入力部品にStoreに保存されている設定値を表示する
ウィンドウアプリを初期表示時に、以前入力していた情報を保持していたいケースがあります。
よくあるのはログイン情報だと思います。
electron-storeモジュールとipcMain,ipcRendererを使って実装してみます。
| Storeキー | Channel |
|---|---|
| window.name | invoke-key |
ロードするhtml(index.html)
最初にロードするindex.htmlは以下です。
<!doctype html>
<html lang="ja">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />
<title>Title</title>
</head>
<body style="background: white;">
<input type="text" id="name" size="27px"><br>
<script src="libs.js"></script>
</body>
</html>
テキストボックスがある画面です。
メインプロセス(index.js)
メインプロセスのjsファイルです。
const { app, BrowserWindow, ipcMain } = require('electron')
const Store = require('electron-store')
const store = new Store()
// ★ipcMain.onでevent.returnValueにセットした値がipcRenderer.sendSyncの戻り値
ipcMain.on('invoke-key', (event, message) => {
event.returnValue = store.get('window.name','')
return
})
function createWindow () {
const win = new BrowserWindow({
width: 800,
height: 600,
icon: __dirname + '/confrage.ico',
center: true,
resizable: true,
webPreferences: {
nodeIntegration: true,
enableRemoteModule: true
}
})
win.loadFile('index.html')
}
app.whenReady().then(createWindow)
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
ipcRenderer.sendSyncの場合は、event.returnValueに返したい値をセットしないといけません。
レンダラープロセス(libs.js)
const { ipcRenderer } = require('electron')
const Store = require('electron-store')
const store = new Store()
const nametext = document.getElementById('name')
// ★ ipcMain.onでevent.returnValueにセットした値が戻り値
nametext.value = ipcRenderer.sendSync('invoke-key', '')
nametext.onblur = function() { // onblur時にstoreに設定
store.set('window.name', nametext.value)
}
ipcRenderer.sendSyncの戻り値をテキストボックスの値に設定します。
これでレンダラープロセスとメインプロセスのIPC通信で初期表示値を前回起動時の値にすることが出来ます。

KHI入社して退社。今はCONFRAGEで正社員です。関西で140-170/80~120万から受け付けております^^
得意技はJS(ES6),Java,AWSの大体のリソースです
コメントはやさしくお願いいたします^^
座右の銘は、「狭き門より入れ」「願わくは、我に七難八苦を与えたまえ」です^^



コメント