2016年8月8日 星期一

[Chrome] Notification 通知視窗




  1. window.addEventListener('load', function () {
  2. //確認使用者是否允許跳窗,如果沒有,就跳窗取權限
  3. if (window.Notification && Notification.permission !== "granted") {
  4. Notification.requestPermission(function (status) {
  5. if (Notification.permission !== status) {
  6. Notification.permission = status;
  7. }
  8. });
  9. }
  10. function NotifyMsg() {
  11. var option = {
  12. tag: 'Notification',
  13. body: '測試測試測試',
  14. data: 'I am a data',
  15. icon: '' //可以自訂ICON
  16. }
  17.  
  18. var n = new Notification("Title", option);
  19. setTimeout(n.close.bind(n), 5000);
  20. console.log(n.data);
  21. n.onclick = function (event) {
  22. event.preventDefault(); // prevent the browser from focusing the Notification's tab
  23. window.open('http://www.google.com.tw/', '_blank');
  24. }
  25. }
  26.  
  27. var button = document.getElementsByTagName('button')[0];
  28. button.addEventListener('click', function () {
  29. // If the user agreed to get notified
  30. // Let's try to send ten notifications
  31. if (window.Notification && Notification.permission === "granted") {
  32. NotifyMsg();
  33. }
  34.  
  35. // If the user hasn't told if he wants to be notified or not
  36. // Note: because of Chrome, we are not sure the permission property
  37. // is set, therefore it's unsafe to check for the "default" value.
  38. else if (window.Notification && Notification.permission !== "denied") {
  39. Notification.requestPermission(function (status) {
  40. if (status === "granted") {
  41. NotifyMsg();
  42. }
  43. // Otherwise, we can fallback to a regular modal alert
  44. else {
  45. alert("Hi!");
  46. }
  47. });
  48. }
  49. // If the user refuses to get notified
  50. else {
  51. // We can fallback to a regular modal alert
  52. alert("Hi!");
  53. }
  54. });
  55. });



參考資料: MDN


沒有留言:

張貼留言