今天发现 hacpai 在收到消息提醒时,右下角会弹出一个长方形的消息框,这个在 Chrome 插件拓展 见过很多次,觉得很有趣,便查了下 API ,折腾出了下面的代码:
二〇一六年四月二十七日支持新版的谷歌浏览器,同时支持火狐
效果如下、
JavaScript:
旧版代码(已失效)
function notify(title, content) { if(!title && !content){ title = "桌面提醒"; content = "您看到此条信息桌面提醒设置成功"; } var iconUrl = "http://imcyk.com/favicon.ico"; if (window.webkitNotifications) { //chrome老版本 if (window.webkitNotifications.checkPermission() == 0) { var notif = window.webkitNotifications.createNotification(iconUrl, title, content); notif.display = function() {} notif.onerror = function() {} notif.onclose = function() {} notif.onclick = function() {this.cancel();} notif.replaceId = 'Meteoric'; notif.show(); } else { window.webkitNotifications.requestPermission($jy.notify); } } else if("Notification" in window){ // 判断是否有权限 if (Notification.permission === "granted") { var notification = new Notification(title, { "icon": iconUrl, "body": content, }); } //如果没权限,则请求权限 else if (Notification.permission !== 'denied') { Notification.requestPermission(function(permission) { // Whatever the user answers, we make sure we store the // information if (!('permission' in Notification)) { Notification.permission = permission; } //如果接受请求 if (permission === "granted") { var notification = new Notification(title, { "icon": iconUrl, "body": content, }); } }); } } } function autoClose(notification) { if (typeof notification.time === 'undefined' || notification.time <= 0) { notification.close(); } else { setTimeout(function() { notification.close(); }, notification.time); } notification.addEventListener('click', function() { notification.close(); }, false) }
新版代码
function showNotice(title, content) { if(!title && !content){ title = "桌面提醒"; content = "您看到此条信息桌面提醒设置成功"; } var iconUrl = "http://imcyk.com/favicon.ico"; if (Notification.permission == "granted") { var notification = new Notification(title, { body : content, icon : iconUrl }); notification.onclick = function() { notification.close(); }; } }
2018年10月25日 新版代码
function showNotice(title, content) { if (!title && !content) { title = "桌面提醒"; content = "您看到此条信息桌面提醒设置成功"; } var iconUrl = "http://imcyk.com/favicon.ico"; Notification.requestPermission(function (perm) { if (perm == "granted") { var notification = new Notification(title, { renotify: "auto", tag: "imcyk", icon: iconUrl, body: content }); } }) }
HTML:
<button onclick="notify('','')"> Notify me! </button>
发布于 2016-05-27 23:27:12 回复