Electron + node.jsで作成したアプリで通知する(Windows)

Electron + node.jsで作成したアプリで通知する(Windows)

メインプロセスとレンダラープロセスで通知を行う事が出来ます。

レンダラープロセスで通知するにはHTML5の通知を利用したNotification APIで実装することが出来ます。

レンダラープロセスで通知

レンダラープロセスで通知します。

通知ボタンをクリックすると右下に通知が表示されます。

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Hello World!</title>
  <script type="text/javascript">
    function notify() {
      new Notification("通知");
    }
  </script>
</head>
<body>
<button onclick="notify()">通知</button>
</body>
</html>

右下に表示される通知です。

Electron + node.jsで作成したアプリで通知する(Windows)

メインプロセスで通知

メインプロセスで通知するには、index.jsを以下のようにします。

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

function createWindow () {
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true
    }
  })

  win.loadFile('index.html')
}

function showNotification () {
  const notification = {
    title: 'タイトル',
    body: '通知'
  }
  new Notification(notification).show()
}

// ★この部分変更する
// app.whenReady().then(createWindow)
app.whenReady().then(createWindow).then(showNotification)

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow()
  }
})

これでウィンドウが表示されてその次に通知が表示されます。

npm startで起動します。

Electron + node.jsで作成したアプリで通知する(Windows)

GitHub - takahashi-h5/electron02
Contribute to takahashi-h5/electron02 development by creating an account on GitHub.

次回はDrag&Dropを実装してみたいと思います。

コメント

タイトルとURLをコピーしました