LoginSignup
12
9

More than 5 years have passed since last update.

electron で通知を使う(Notification)

Posted at

デスクトップアプリをさっくり作れてしまう electron ですが、通知に関してドハマリしました。お役に立てるかどうか微妙な情報ですが、まとめておきます。

投稿するつもりなんて全然なかったんですが、「下書き多すぎ」ってシステムに叱られたんで公開することにしました

electron の通知(Notification)種類

electron の通知システムは呼び出し場所により大きく2種類に別れます。

renderer process で利用

HTML5 Notification API を利用することが出来ます。
Notifications (Windows, Linux, macOS)

main process で利用

Class: Notification が用意されています。
Create OS desktop notifications

ここから本題

上記の2つのうちのどちらかで対応できれば幸せなのですが、実は Windows10 の環境で「通知がされない」という、不具合を踏んでしまいました。。。
手元の環境(Windows7)では通知され、Windows10 でも一部の環境では動いてしまったので、かなり困りました^^;

Notification API do not work with Windows 10 16299.19 (fall creators update) #10864

色々原因があるようで、対処方法もきちんとクローズされているものからおまじないレベルまで様々です。

解決方法

当方豪腕なので、当然力技代替案ですw
ちっちゃいフレームなしブラウザを表示することで対応しました。
main process に「通知ブラウザ」を用意します。

Node.js
    const { screen } = require('electron');
    const { width, height } = screen.getPrimaryDisplay().workAreaSize
    notifyWindow = new BrowserWindow({
        title: "notify message",
        frame: false,
        show: false,
        x: width - 290,
        y: height - 120,
        width: 280, 
        height: 80,
        icon: path.join(__dirname, '/public/icon.png'),
        setMenu: null,
        skipTaskbar:true
    });
    notifyWindow.loadURL(url.format({
        pathname: path.join(__dirname, 'notify.html'),
    }))
    notifyWindow.setAlwaysOnTop(true)

あとは、条件合致で show してあげればよいです。

electron 利用アプリで正しく通知できているものもあるので、根治できる気もしますが、趣味のアプリであればさっさと見切りつけて代替案採用したほうが手っ取り早いです。

おまけ

条件合致で show する時に、音出したい場合はブラウザ起動時にオプションを追加して上げる必要があります。
DOMException: play() failed because the user didn't interact with the document first. #14323

Node.js
const {
  app,
  BrowserWindow,
  ipcMain
} = require('electron')
app.commandLine.appendSwitch('--autoplay-policy','no-user-gesture-required')
12
9
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
12
9