コード:https://github.com/mo49/electron_test
node-machine-idを使用する
webview
サイトを読み込む準備
index.html
<webview id="webview" src="https://www.google.co.jp/" autosize="on"></webview>
ipcMain | プロセス間通信
Electronで実行するJS
main.js
const path = require('path');
const url = require('url');
const {app, BrowserWindow, ipcMain} = require('electron');
const {machineId} = require('node-machine-id');
let mainWindow;
app.on('ready', () => {
machineId().then(id => {
createWindow();
ipcMain.on('webview-ready', event => {
// channel経由でレンダラープロセスに非同期に返信し、任意の引数を渡す
// ipcMain.send()ではない点に注意
event.sender.send('machine-id',id); // ipcRenderer.on('machine-id')で受ける
})
})
});
function createWindow() {
mainWindow = new BrowserWindow({width:800,height:600});
mainWindow.loadURL(url.format({
pathname: path.join(__dirname, 'src/index.html'),
protocol: 'file',
slashes: true,
}));
mainWindow.on('closed', function() {
mainWindow = null;
})
}
参考
https://github.com/electron/electron/blob/master/docs-translations/jp/api/ipc-main.md
ipcRenderer | プロセス間通信
index.htmlで読み込むapp.js
app.js
const {ipcRenderer} = require('electron');
const webview = document.querySelector('webview');
// dom-readyはあらかじめ登録されているイベント
webview.addEventListener('dom-ready', () => {
ipcRenderer.on('machine-id', (event, machineId) => {
webview.executeJavaScript(`window.onApplicationReady && window.onApplicationReady("${machineId}");`)
console.log(machineId);
})
ipcRenderer.send('webview-ready'); // ipcMain.on('webview-ready')で受ける
})
参考
https://github.com/electron/electron/blob/master/docs-translations/jp/api/ipc-renderer.md
webviewで読み込んだサイト内でJSを実行
window.onApplicationReady
は、
webviewで読み込んだサイトの中で実行できるJS
つまり読み込んだサイト内のJSで、machineIdを使用することができるようになった
window.onApplicationReady = (uuid) => {
console.log(uuid);
}
参考
https://github.com/electron/electron/blob/master/docs/api/web-contents.md