I just ask permission once, then I let the user configure whether he wants to receive notifications from the configuration panel.
localStorage.
if (notificationsEnabled) {
var notification = new window.Notification("Hello");
}
$(function () {
notificationsEnabled = JSON.parse(localStorage.getItem('notificationsEnabled') || false);
$('#notificationsEnabled').prop('checked', notificationsEnabled);
if (!window.Notification) {
$('#notificationsEnabled').prop('disabled', true);
}
});
<label>
<input id="notificationsEnabled" name="notificationsEnabled" type="checkbox">
Enable notifications
</label>
onchange
$('#notificationsEnabled').on('change', function() {
notificationsEnabled = !notificationsEnabled;
localStorage.setItem('notificationsEnabled', notificationsEnabled);
if (notificationsEnabled && window.Notification.permission === 'default') {
window.Notification.requestPermission();
}
});