【1】Web Notifications APIがサポートされているブラウザか確認
if ("Notification" in window) {
// サポートされている
} else {
// サポートされていない
}
サンプル
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Notification Demo</title>
</head>
<body>
<button onclick="checkSupportOrNot()">Check</button><br />
</body>
<script type="text/javascript">
function checkSupportOrNot() {
if ("Notification" in window) {
var notify = new Notification("Support!", {});
} else {
alert("Not Support!!");
}
}
</script>
</html>
参考文献
https://developer.mozilla.org/ja/docs/Web/API/notification
【2】指定した時間で通知を閉じる
setTimeout(function() {
【Notificationインスタンス】.close();
}, 【時間】);
サンプル
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Notification Demo</title>
</head>
<body>
<button onclick="sayHello()">Hi</button><br />
</body>
<script type="text/javascript">
function sayHello() {
if(window.Notification && Notification.permission !== "denied") {
Notification.requestPermission(function(status) {
var notify = new Notification(
'Title ... Say Hello!', {
body: 'Body ... Say World!!',
icon: 'https://ident-001.west.edge.storage-yahoo.jp/res/ident-5mypszyrqsxdfvywx6dmdr5oam/profile/icon_sr?1274278682'
});
// ★3秒後消す★
setTimeout(function() {
notify.close();
}, 3000);
});
}
}
</script>
</html>