Last active
January 20, 2018 12:17
-
-
Save semlinker/ddd190ad269c0866bbd2e35b4d4009a7 to your computer and use it in GitHub Desktop.
PWA 学习笔记之 Web Notifications API Demo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>Web Notifications API</title> | |
</head> | |
<body> | |
<button id="notificationsBtn">发送通知</button> | |
<script> | |
document.addEventListener('DOMContentLoaded', initNotification, false); | |
function initNotification() { | |
if (!('Notification' in window)) { | |
alert('当前浏览器不支持通知!'); | |
} else if (Notification.permission === 'denied') { | |
console.log('用户拒绝通知权限!'); | |
} else if (Notification.permission === 'granted') { | |
console.log('用户允许通知权限!'); | |
} | |
// 创建通知对象 | |
function createNotification() { | |
var notification = new Notification("Introducing WhatFontIs is the Easiest Way to Identify Fonts Online", | |
{ | |
body: "A free service to help you ...", | |
icon: "https://dab1nmslvvntp.cloudfront.net/wp-content/uploads/2017/10/1507698696SitePoint@2x-96x96.png", | |
}); | |
notification.onclick = () => { | |
window.open('https://www.sitepoint.com/finding-fonts-whatfontis/'); | |
}; | |
return notification; | |
} | |
// 监听发送通知操作 | |
document.querySelector('#notificationsBtn').addEventListener('click', () => { | |
if(Notification.permission === 'granted') { | |
createNotification(); | |
} else { | |
// 可能的状态为:denied或default,若状态为denied则requestPermission方法无效 | |
Notification.requestPermission(function(permission) { | |
// 如果用户同意,就可以向他们发送通知 | |
if (permission === "granted") { | |
createNotification(); | |
} | |
}); | |
} | |
}); | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment