html5桌面通知
/**
* 桌面提醒
* @description 只支持 谷歌,火狐,360Chrome模式, 在不支持的浏览器不做任何处理, 如果是cmd/amd请根据自己的需求打包, 会在页面加载时会请求用户授权, 如果已授权或者拒绝的跳过
* @author guoliang && xieliang
*
* @example
* 1, new notification("我是标题");
* 2, notification("我是标题");//new不new都一样, 但我希望你new
* 3, new notification("我是标题", "我是内容");
* 4, new notification("我是标题", {icon: 'icon地址'});
* 5, var a = new notification("我是标题", {onclick: function(){}, onshow: function(){}, onclose: function(){}}); 外部关闭a.close();
* 6, new notification("我是标题", {time: 3000});//自动关闭
*/
(function(window) {
var not = !!window.Notification,
noop = function() {},
request;
//如果支持
if (not && Notification.permission === 'default') {
document.addEventListener('click', request = function() {
Notification.requestPermission();
//卸载事件
document.removeEventListener('click', request);
request = null;
}, false);
}
// 构造函数
function notification(options, content) {
var self = this,
temp;
if (!(self instanceof notification)) {
return new notification(options, content);
}
//('title')
if ('string' === typeof options) {
if ('string' === typeof content) { //(title, content)
options = {
title: options,
body: content
}
} else if ('object' === typeof content) { //(title, {})
temp = options;
options = content;
options.title = temp;
} else if ('number' === typeof content) {
options = {
title: options,
time: content
}
} else {
options = {
body: options
}
}
} else {
options = Object.prototype.toString.call(options) === '[object Object]' ? options : {};
}
for (temp in notification.defaults) {
options[temp] = options[temp] || notification.defaults[temp];
}
//创建实例
temp = self.Not = new Notification(options.title, options);
//添加事件
temp.onclick = options.onclick;
temp.onshow = options.onshow;
temp.onclose = function() {
delete self.Not;
options.onclose.call(this);
}
//如果有定时器
if (options.time) {
setTimeout(function() {
self.close();
}, options.time);
}
return self;
}
//如果不支持 ~_~ 或者已禁用
if (!not || Notification.permission === 'denied') {
notification = noop;
}
/**
* 关闭
*/
notification.prototype.close = function() {
var self = this;
if (self.Not) {
self.Not.close();
}
return self;
}
// 默认参数
notification.defaults = {
title: "提示",
body: "内容",
// 标签类别
tag: "",
// 通知图标
icon: "http://static.easywed.cn/dist/images/lib/logo-60-40.png",
// 显示通知
onshow: noop,
// 关闭通知
onclose: noop,
// 单击通知
onclick: noop,
time: 3000 //s
}
//如果是cmd||amd
if (typeof define === "function" && (define.amd || define.cmd)) {
define(function() {
return notification;
});
} else {
window.notification = notification;
}
})(window);
本文链接:https://xuexb.com/post/231.html
-- EOF --
发表于 2014年09月18日 16:34:37 ,添加在分类 前端技术 下 ,最后修改于 2017年03月29日 21:26:41
提醒: 本文最后更新于 3209 天前,文中所描述的信息可能已发生改变,请谨慎使用。
Comments
注:如果长时间无法加载,请针对 disq.us | disquscdn.com | disqus.com 启用代理。