So basically I have button which when clicked will trigger a call to Notification.requestPermission and depending on the users response I do some action.
The issue is that Notification.requestPermission does not actually fire when it is automatically blocked by Chrome.
This is my code
function askNotificationPermission(handler) {
// checks to see if notification is actually supported
function checkNotificationPromise() {
try {
// checks if promise based notification is okay
Notification.requestPermission().then();
} catch(e) {
return false;
}
return true;
}
// Let's check if the browser supports notifications
if (!('Notification' in window)) {
console.log("This browser does not support notifications.");
} else {
if(checkNotificationPromise()) {
window.console.log("requesting permission...")
Notification.requestPermission()
.then((permission) => {
window.console.log("PERMISSION", permission)
handler(permission);
window.console.log("finished handler")
})
window.console.log("done", Notification.permission)
} else {
Notification.requestPermission(function(permission) {
handler(permission);
});
}
}
}
Is there anyway to catch when notifications are automatically blocked?
Related
My website currently sends push notifications to users when accessing the site for the first time, is there a way to remove this push notification request?
TIA
Use this in your .js file
Notification.requestPermission();
Create a button for "Enable Notification" in .html file
<button id="enable">Enable notifications</button>
When pressing this button app requests notification for the app (.js file)
function askNotificationPermission() {
// Asking for permissions
function handlePermission(permission) {
// button set for shown or hidden, depending on the user's selection
if(Notification.permission === 'denied' || Notification.permission === 'default') {
notificationBtn.style.display = 'block';
} else {
notificationBtn.style.display = 'none';
}
}
// Check if the browser actually supports notifications
if (!('Notification' in window)) {
console.log("This browser does not support notifications.");
} else {
if(checkNotificationPromise()) {
Notification.requestPermission()
.then((permission) => {
handlePermission(permission);
})
} else {
Notification.requestPermission(function(permission) {
handlePermission(permission);
});
}
}
}
Is there a way to check if the service worker found an update before loading custom functions?
i have this function which is working, but it runs the custom functions twice, and seems very untidy..
I'm looking for a way to only run the custom functions once, and not when an update was found and installed. When an update is found, the user || the page will reload automatically and then the custom functions can run normally..
I added the reg.events in this function to determine where to place my custom functions. I hope this question is understandable..
function installApp(path, scope) {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register(path, {
scope: scope
}).then((reg) => {
// event listener to catch the prompt if any and store in
// an instance for later use with add to homescreen() function.
getPrompt();
// this is a custom alert type notification
makeProgress('System','is ok');
/* THIS IS THE UPDATE FOUND FUNCTION */
reg.onupdatefound = function() {
var installingWorker = reg.installing;
installingWorker.onstatechange = function() {
switch (installingWorker.state) {
case 'installed':
if (navigator.serviceWorker.controller) {
// the _clear() function removes items from the locaforage db to
// force the app to not auto login, but let the user
// login again to refresh any data when the page reloads
_clear('uuid');
_clear('user');
_clear('token');
makeProgress('new version','reload app');
} else {
// removes any custom notifications
clearProgress();
//just go into the app because everything is loaded.
//We dont need to reinstall the
//homescreen or listen for the homescreen because this
//is an update and the homescreen should already be installed?
enterApp();
}
break;
case 'redundant':
// removes any custom notifications cause
//the install is complete
clearProgress();
enterApp();
console.log('The installing service worker became redundant.');
break;
}
};
return;
};
/** Here is the events that fire during the install
// process and where i am currently stuck **/
if (reg.installing) {
makeProgress('updating','files');
/* THE SERVICE WORKER IS DOWNLOADING THE CACHE FROM THE SERVER */
} else if (reg.waiting) {
/* what message here ?*/
/* as far as i can tell, THE SERVICE WORKER IS WAITING FOR
*//*PREVIOUS SERVICE WORKER TO BEREFRESHED SO A RELOAD */
/*UI SHOULD COME HERE??*/
} else if (reg.active) {
/* what message here ?*/
/* IS THIS THE BEST PLACE TO RUN THE BELOW CUSTOM
*//*FUNCTIONS?? WILL //THEY ALWAYS FIRE */
}
/** AT WHICH OF THE EVENTS ABOVE WILL I ADD THE FUNCTIONS FROM HERE **/
requestWakeLock();
const browserFeatures = detectFeatures(reg);
setCompatibilityArray(browserFeatures);
localforage.ready().then(function() {
localforage.getItem('homescreen').then(function (value) {
if(value != 1){
if (platform == 'iPhone' || platform == 'iPad') {
installHome();
} else {
makeProgress('waiting', 'prompt');
waitPrompt();
}
return;
} else {
enterApp();
return;
}
}).catch(function (err) {
alertIt('something went wrong. Please refresh the page to try again. If the problem persists, try another browser.</br>', 'warning', 0);
return;
});
}).catch(function (err) {
alertIt('Something went wrong.<br>Please refresh the page to restart the installation process.<br>'+err, 'danger', 0);
return;
});
/** TO HERE, WITHOUT RUNNING THESE FUNCTION DURING*/
/*THE ONUPDATEFOUND EVENT AS THEN THEY WILL RUN TWICE**/
}, (err) => {
alertIt('Something went wrong.<br>Please refresh the page to restart the installation process.<br>', 'danger', 0);
})
} else {
alertIt('This browser is not compatible with this app.<br>Please try to use a different browser to install this application.<br>', 'danger', 0);
return;
}
}
I initialize this script like so:
window.addEventListener("load", () => {
makeProgress('Checking','system');
installApp(appsPath, appScope);
})
basically they must not be invoked if a new update is found..
I discovered that the onupdate function runs when old service worker is active..
If the onupdate function fires it changes a variable to a true value
I then used a time out function in the active event to see if a variable had changed... if it did change then i return false, and let the onupdate functions continue their course.. otherwise i continue to load my custom functions...Its working, but it doesn't seem like the best way.
Do you have a better method?
so like this:
function installApp(path, scope) {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register(path, {
scope: scope
}).then((reg) => {
getPrompt();
makeProgress('refreshing','files');
var entApp = true;
reg.onupdatefound = function() {
entApp = false;
var installingWorker = reg.installing;
installingWorker.onstatechange = function() {
switch (installingWorker.state) {
case 'installed':
if (navigator.serviceWorker.controller) {
_clear('uuid');
_clear('user');
_clear('token');
makeProgress('new version','reloading app');
setTimeout(function(){
location.reload();
}, 2500);
return;
} else {
/*NOT SURE WHAT IS SUPPOSED TO GO HERE, SO I JUST RELOADED THE PAGE*/
makeProgress('new version','reloading app');
setTimeout(function(){
location.reload();
}, 2500);
return;
}
break;
case 'redundant':
/*NOT SURE WHAT IS SUPPOSED TO GO HERE, SO I JUST RELOADED THE PAGE*/
makeProgress('new version','reloading app');
setTimeout(function(){
location.reload();
}, 2500);
return;
break;
}
};
return;
};
if (reg.active) {
/** RIGHT HERE IS WHERE THE ONUPDATE FIRES. I GAVE IT A
2.5 SECONDS TO DO ITS THING, THEN CHECKED TO SEE IF THERE WAS
AN UPDATE, IF NO UPDATE THEN I RUN MY CUSTOM FUNCTIONS, OTHERWISE
THE ONUPDATE FUNCTION RELOADS THE PAGE AND THE UPDATED SW.JS FILE
WILL THEN RUN THESE FUNCTIONS WHEN ITS ACTIVE.. IS THERE A BETTER
IN-BUILT METHOD TO DO THIS?**/
setTimeout(function(){
if(entApp === true){
requestWakeLock();
const browserFeatures = detectFeatures(reg);
setCompatibilityArray(browserFeatures);
localforage.ready().then(function() {
localforage.getItem('homescreen').then(function (value) {
if(value != 1){
if (platform == 'iPhone' || platform == 'iPad') {
installHome();
} else {
makeProgress('waiting', 'prompt');
waitPrompt();
}
return;
} else {
enterApp();
return;
}
}).catch(function (err) {
alertIt('something went wrong. Please refresh the page to try again. If the problem persists, try another browser.</br>', 'warning', 0);
return;
});
}).catch(function (err) {
alertIt('Something went wrong.<br>Please refresh the page to restart the installation process.<br>'+err, 'danger', 0);
return;
});
}
}, 2500);
}
what i wanted to do is only show the notification after the notification allowed.
what i have right now is, every after refresh on page it is always showing the notifications
this is my javascript
function notifyMe() {
function AutoRefresh( t ) {
setTimeout("location.reload(true);", t);
}
// Let's check if the browser supports notifications
if (!("Notification" in window)) {
alert("This browser does not support desktop notification");
}
// Let's check whether notification permissions have already been granted
else if (Notification.permission === "granted") {
// If it's okay let's create a notification
var notification = new Notification('{!! $myname->body !!}');
notification.onclick = function(event) {
event.preventDefault(); // prevent the browser from focusing the Notification's tab
window.open('http://localhost:8000/spektra/spektra-memberikan-aneka-tawaran-di-jakarta-fair-kemayoran-2018', '_blank');
}
}
// Otherwise, we need to ask the user for permission
else if (Notification.permission !== "denied") {
Notification.requestPermission().then(function (permission) {
// If the user accepts, let's create a notification
if (permission === "granted") {
var notification = new Notification('{!! $myname->body !!}');
notification.onclick = function(event) {
event.preventDefault(); // prevent the browser from focusing the Notification's tab
window.open('http://localhost:8000/spektra/spektra-memberikan-aneka-tawaran-di-jakarta-fair-kemayoran-2018', '_blank');
}
}
});
}
}
what should i do to make the notification only once, even after refresh.
You have to track if the user has already seen the notification and, if so, skip the rest of your notifyMe function. For example, you could store the information in localStorage.
function notifyMe() {
function AutoRefresh(t) {
// passing strings to setTimeout makes me shiver
// too many years of avoiding eval and stuff i guess :)
setTimeout(function () { location.reload(true); }, t);
}
if (localStorage.getItem('userHasSeenNotification')) {
return; // early return, exits the function
}
if (!('Notification' in window)) {
alert('Notifications ... ');
return; // early return, lets us get rid of the "else"
}
// Let's check whether notification permissions have already been granted
if (Notification.permission === "granted") {
// save seen state
localStorage.setItem('userHasSeenNotification', 1);
// If it's okay let's create a notification
var notification = new Notification('{!! $myname->body !!}');
notification.onclick = function(event) {
event.preventDefault(); // prevent the browser from focusing the Notification's tab
window.open('http://localhost:8000/spektra/spektra-memberikan-aneka-tawaran-di-jakarta-fair-kemayoran-2018', '_blank');
};
return; // ... again ...
}
// Otherwise, we need to ask the user for permission
if (Notification.permission !== "denied") {
// save seen state
localStorage.setItem('userHasSeenNotification', 1);
Notification.requestPermission().then(function (permission) {
// If the user accepts, let's create a notification
if (permission === "granted") {
var notification = new Notification('{!! $myname->body !!}');
notification.onclick = function(event) {
event.preventDefault(); // prevent the browser from focusing the Notification's tab
window.open('http://localhost:8000/spektra/spektra-memberikan-aneka-tawaran-di-jakarta-fair-kemayoran-2018', '_blank');
};
}
});
}
}
}
Hint: You might want to move that last localStorage.setItem call into the callback passed to .then(function (permission) { ... }).
How can I catch with serviceworker or simple js code, when user who previously allowed the web push notifications for my site disable them? For Firefox and Chrome browsers.
You can use the Permissions API to detect the current state of given permissions, as well as listen for changes.
This article has more detail. Here's a relevant code snippet:
navigator.permissions.query({name: 'push'}).then(function(status) {
// Initial permission status is `status.state`
status.onchange = function() {
// Status changed to `this.state`
};
});
You can try this:
navigator.permissions.query({name:'notifications'}).then(function(status) {
//alert(status.state); // status.state == { "prompt", "granted", "denied" }
status.onchange = function() {
if(this.state=="denied" || this.state=="prompt"){ push_unsubscribe(); }
};
});
or this:
navigator.permissions.query({name:'push', userVisibleOnly:true}).then(function(status) {
//alert(status.state); // status.state == { "prompt", "granted", "denied" }
status.onchange = function() {
if(this.state=="denied" || this.state=="prompt"){ push_unsubscribe(); }
};
});
I use it to send information to the server that the user has canceled or disabled notifications. Note that the code is not executed if the user does so in the site settings.
So i've got a main page where there's 3 buttons - login, register and recover account. I want to disable all those buttons and display a message when geolocation is unavaliable or the user has not allowed the browser to share it's location.
$scope.btnDisabled = false;
$scope.errorMsg = null;
$scope.checkBrowser = function () {
if (navigator.geolocation.getCurrentPosition) {
// let's find out where you are!
console.log("Got your location");
$scope.btnDisabled = false;
} else {
$scope.errorMsg = "Warning. Could not locate your position. Please enable your GPS device.";
//disable the buttons
$scope.btnDisabled = true;
//Show errorMessage
return true
}
//errorMessage visibility is set false
return false;
}
So far i haven't managed to disable the buttons or show errorMessage(except for an alert message).
This is how i got the alert message:
function getPosition() {
console.group("geoloc getPosition");
if (window.navigator) {
console.log("api supported");
navigator.geolocation.getCurrentPosition(success, error);
} else {
console.log("api fallback");
}
console.groupEnd();
}
function success(pos) {
console.log("geoloc pos ", pos);
}
function error(err) {
alert("Geolocation identification failed.");
$scope.btnDisabled = true;
}
Why doesn't the $scope.btnDisable work in error() function?
You should use
navigator.geolocation.getCurrentPosition(
function() {
$scope.btnDisabled=false;
$scope.$apply();
}, function() {
$scope.btnDisabled=true;
$scope.$apply();
}
});
It is verry important to know, that getCurrentPosition will call a callback instead of returning something! See https://developer.mozilla.org/en-US/docs/Web/API/Geolocation.getCurrentPosition
You've also to call $scope.$apply() as you'll disable any angular updates while processing non angular callbacks!
Do so in your 2nd example and the button state should get updated