我正在尝试使用jQuery在页面加载时本地显示通知。 通知在Firefox,Firefox Developer和Chrome中正确显示。 尽管在通知首选项设置中允许,但Safari中未显示通知。
相似的代码在MDN网站https://developer.mozilla.org/en/docs/Web/API/notification上运行良好。
代码片段如下。
// Display a sample notification
if (window.Notification) {
return $(".au-notifications-page").show(function() {
var notification;
notification = new Notification(
'Success Text', {
//tag: $("[name=tag]").val(),
body: 'Success Message',
iconUrl: 'img/avatar-male.png',
icon: 'img/avatar-male.png'
});
return notification.onclick = function() {
notification.close();
window.open().close();
return window.focus();
};
});
};
完整代码如下。
$(document).ready(function () {
// Request permission on site load
Notification.requestPermission().then(function(result) {
if (result === 'denied') {
//alert('denied');
$(".au-notif-disabled-header").removeClass('hide');
$(".au-notif-disabled-header .btn").addClass('hide');
return;
}
if (result === 'default') {
//alert('ignored');
$(".au-notif-disabled-header").removeClass('hide');
return;
}
//alert('granted');
$(".au-notif-disabled-header").addClass('hide');
});
// Request permission with button
$('.au-notif-disabled-header .btn').click(function () {
Notification.requestPermission().then(function(result) {
if (result === 'denied') {
$(".au-notif-disabled-header").removeClass('hide');
$(".au-notif-disabled-header .btn").addClass('hide');
return;
}
if (result === 'default') {
$(".au-notif-disabled-header").removeClass('hide');
return;
}
$(".au-notif-disabled-header").addClass('hide');
});
});
$( ".au-notification-icon" ).hover(
function() {
$(".au-notifications-menu .au-notif-msg-realtime").slideDown();
$('.au-notification-icon .badge').html("2");
}, function() {
$(".au-notifications-menu .au-notif-msg-realtime").slideUp();
$('.au-notification-icon .badge').html("1");
}
);
//To show notification received while on notifications page
$(".au-notif-msg-realtime").hide();
//$(".au-notifications-page .au-notif-msg-realtime").slideDown();
$(".au-notifications-page .au-notif-msg-realtime").slideDown({
complete: function(){
$('.au-notification-icon .badge').html("2");
$('head title').html("(2) Notifications");
}
});
// Display a sample notification
if (window.Notification) {
return $(".au-notifications-page").show(function() {
var notification;
notification = new Notification(
'Success Heading', {
body: 'Success Text',
iconUrl: 'img/avatar-male.png',
icon: 'img/avatar-male.png'
});
return notification.onclick = function() {
notification.close();
window.open().close();
return window.focus();
};
});
};
});
编辑1: Safari抛出以下异常
未定义的对象(评估'Notification.requestPermission().then')