Pushing a browser notification when a threshold is met - javascript

I've got the following piece of code (a basic notification that is pushed if the user permits such). My final goal is to have such a notification appear everytime a certain parameter's value reaches a threshold in my project. Let's say I have a live tracker of how many people are in a certain place. If that value passes 50, push a notification. I have not found anything similar and I am unsure where to start from with this.
<script>
function showNotification() {
const notification = new Notification("New message form Scenwise", {
body: "just testing if this notification works"
})
}
if (Notification.permission === "granted") {
showNotification();
}
else if (Notification.permission !== "denied") {
Notification.requestPermission().then(permission => {
if (permission === "granted") {
showNotification();
}
})
}
</script>

Assuming this parameter is a variable you're maintaining in your javascript and only your code is updating the value of this variable, you should be able implement logic every time you update its value to check if it meets your threshold, and push a notification if necessary.
If you need a more automated solution, this might be helpful to you: Listening for variable changes in JavaScript

Related

I can't realise what is wrong with this piece of code - Notification.requestPermission();

Take a look at the example JavaScript - Explain what issues implementing this onto your site may cause and explain how it could be prevented:
(function() {
Notification.requestPermission();
})();
I've the exercise above and I can't figure out what is wrong with it.
There might be a few issues that come from this code.
1. Not checking if Notification is supported
In some browsers, Notification isn't supported. Due to this, you have to check if it is in the window, otherwise it will throw an error.
To do this, you can use the following code.
if (!("Notification" in window)) {
console.log("Your browser doesn't support notifications.");
} else {
Notification.requestPermission();
}
This will check if Notification isn't in the global window object (basically, checking if window.Notification is undefined).
2. Not checking if Notification has already been granted
Another thing that could be the issue is the fact that you aren't checking if Notification has already been granted. This can cause annoyance with the user.
To check if it has already been granted before asking the user for permission, you can add an if/else statement, like so.
if (Notification.permission === "granted") {
const notification = new Notification("Hello, world!");
} else {
Notification.requestPermission();
}
This checks if the permission is granted, so that you can just send the notification without pestering the user with confirmation dialogs.
3. Not using a Promise
The function Notification.requestPermission() used to have a callback instead of a Promise. But, in favour of Promises, it is now deprecated.
According to MDN Web Docs on the callback parameter:
An optional callback function that is called with the permission value. Deprecated in favor of the promise return value.
Due to this, you need to use a Promise with the function.
Important: Safari doesn't yet support the Promise method. You need to use callbacks instead.
To do this, you can simply use the code below.
Notification
.requestPermission()
.then((permission) => {
if (permission === "granted") {
const notify = new Notification("Hello, world!");
}
});
Basically, this code will run the .then() method when the user has accepted/denied the notification access.
There are three possible values for the permission parameter in the .then() method.
Value
Description
granted
The user has granted permission for notifications.
denied
The user has denied permission for notifications.
default
Default option.
If the user has granted permission, we send them a notification using the Notification class.
In conclusion, there are three issues that I have spotted in this code.
Not checking if Notification is supported
Not checking if Notification has already been granted
Not using a Promise
All of the code extracted from these solutions result in this code below. You can use this code, which will rid all of the issues.
(function () {
// 1. Not checking if Notification is supported
if (!("Notification" in window)) {
console.log("Your browser doesn't support notifications.");
}
// 2. Not checking if Notification has already been granted
else if (Notification.permission === "granted") {
const notification = new Notification("Hello, world!");
}
// 3. Not using a Promise
else {
Notification
.requestPermission()
.then((permission) => {
if (permission === "granted") {
const notify = new Notification("Hello, world!");
}
});
}
})();
These are the issues that I think could come from this code.

save/remember an Alexa user's intent confirmation response?

I have a confirmation prompt for one of my Alexa skill's intents, and now I need it to "remember" the user's answer and not ask the user again. Essencially, we want the user to be prompted only on the very first time they use the skill, and then never again. Is that possible?
I'm hoping I don't have to do a total code re-write, and can just update my existing code. Here is my intent's javascript code (simplified) for the lambda function for the skill:
'myIntent': function() {
// there is a required prompt setup in the language interaction model (in the Alexa Skill Kit platform)
// To use it we "deligate" it to Alexa via the delegate dialoge directive.
if (this.event.request.dialogState === 'STARTED') {
// Pre-fill slots: update the intent object with slot values for which
// you have defaults, then emit :delegate with this updated intent.
this.emit(':delegate');
} else if (this.event.request.dialogState !== 'COMPLETED'){
this.emit(':delegate');
} else {
// completed
var intentObj = this.event.request.intent;
if (intentObj.confirmationStatus !== 'CONFIRMED') {
// not confirmed
if (intentObj.confirmationStatus !== 'DENIED') {
// Intent is completed, not confirmed but not denied
this.emit(':tell', "You have neither confirmed or denied. Please try again.");
} else {
// Intent is completed, denied and not confirmed
this.emit(':ask', 'I am sorry but you cannot continue.');
}
} else {
// intent is completed and confirmed. Success!
var words = "You have confirmed, thank you!";
this.response.speak(words);
this.emit(':responseReady');
}
}
},
Thanks for any help!
Update: I have successfully implement this new feature using the accepted answer's help. However I had to totally re-write everything to fit the new version of the Alexa sdk.
You can persist/save/remember alexa user's data using persistent attributes.
I recommend you to follow alexa skill sample tutorial zero to hero it summarise everything you need to know about developing a skill on Alexa with examples & videos.
And what you need from this tutorial is the Part 4 - Persistence
And then, it will be as easy as:
attributesManager.setPersistentAttributes(sessionAttributes);
await attributesManager.savePersistentAttributes();

Storing DeviceOrientationEvent and DeviceMotionEvent permissions across pages

I've got a nice DeviceMotionEvent request all working for Safari (or other browsers that require the permission), something along these lines:
// on click of a button
DeviceMotionEvent.requestPermission()
.then(response => {
if (response == 'granted') {
// do my thing
}
})
.catch(function(error) {
console.log(error);
// do my other thing
});
And thats working great. But when a user goes to a new page, they have to request the permission again. Obviously I'm calling 'requestPermission' again, so of course they would do.
How do I find out if permission has already been granted? Or is permission granted on a page by page basis (rather than session / site basis)?
I could store the response in localstorage or something, but would prefer something along the lines of:
DeviceMotionEvent.permissionStatus
Or something?
I think you only option is to build a single page application and use the history.pushState() to update the location in the browser, when you wish to ‘change pages’.
Edited:
You can use the Web Storage API with the following two mechanisms:
sessionStorage
localStorage
As the names imply, these two interfaces are ideal for session-based data or if you want to persist state even after the connection is closed.
You should be able to check whether permissions have been granted using the devicemotion eventListener. Baring in mind you have to push a button or similar to run DeviceMotionEvent.requestPermission()
eg.
let hasOrientationControls = false;
window.addEventListener("devicemotion", () => {
hasOrientationControls = true;
});
// then when the button is pressed we can request permissions if we need
onButtonPressed () => {
if (hasOrientationControls) return;
else DeviceMotionEvent.requestPermission();
}
I've also used this
isVRReady = window.DeviceOrientationEvent && "ontouchstart" in window;

How to verify if a check box is checked?

I am currently trying to make my checkbox show a popup for browser notifications if it is checked. If the user unchecked it the browser notification will popup to declined vice-versa.
here is a snippet of what I am trying right now but it is not working.
if(checkbox_id == (queue_notification)) {
if(checkbox_state) {
$('input#user_hop_queue_notification').is(':checked') == '1'
if(Notification.requestPermissionre !== "granted"){
Notification.requestPermission(function(status) {
console.log('Notification permission status:', status);
});
}
}
else {
$('input#user_hop_queue_notification').is(':checked')== ('0');
if(Notification.requestPermission !== "denied"){
Notification.requestPermission(function(status) {
console.log('Notification permission status:', status);
});
}
}
}
The NotificationApi is something that the user can deny also so you even if you set the Notification.permission property to granted that will not work. So your best chance is to use the Notification.requestpermission method and check if the user has granted notification access then use to notification api to show notifications. Thanks.
Your code looks very weird, you seem to test the value of is(':checked'), but you actually do not (no if-statement??). There is a variable checkbox_state which is tested but not set? And, you seem to test if the value of is(':checked') returns the string 0 or 1. While this works, if you test this manually in the console, or check the documentation, you would see it returns true or false, so that could make your code a lot simpler too.
So I would write your code as follows:
if(checkbox_id == (queue_notification)) {
checkbox_state = $('input#user_hop_queue_notification').is(':checked');
if(checkbox_state) {
if(Notification.requestPermissionre !== "granted"){
Notification.requestPermission(function(status) {
console.log('Notification permission status:', status);
});
}
} else {
if(Notification.requestPermission !== "denied"){
Notification.requestPermission(function(status) {
console.log('Notification permission status:', status);
});
}
}
}
If I understood your intention correctly, this should work more as expected. We could refactor the check_state variable away, as we have no further use for it (but for now I wanted to stay closer to your original code)(it might still improve readability, so that would be a good reason to keep it, however the is(:checked) is pretty self-explanatory on its own).
If you are trying to set the checked state, you should use the following code:
$('input#user_hop_queue_notification').prop('checked', true);
(if not obvious, true will "check" the checkbox, false will uncheck).

SharePoint JavaScript Desktop Notification Issue

I have a really strange JavaScript issue that I haven't found any precedent for so hoping someone has seen it.
I'm working on some JavaScript code that resides in SharePoint and I'm trying to use desktop notifications for my Firefox and Chrome users.
I have the following code as just a basic test
$(document).ready(function() {
if ((window.Notification) && (Notification.permission !== "granted")) {
Notification.requestPermission(function(status) {
if (Notification.permission != status) Notification.permission = status;
});
}
if (Notification.permission === "granted") {
var Notification = new Notification("This is a test");
}
});
If I use this code in a custom web page outside of SharePoint it works perfectly fine. If I load it in SharePoint though it's sporadic; some pages it will work just fine but other pages I get an error saying that Notifcation.requestPermission isn't a function. If I do a console.log on the Notification object and Notification.permission I get different results depending on whether I'm on a working page or not working page. On a working page I see Notification as a function with all the correct parameters and Notification.permission comes up as "granted"; the not working pages has Notification as a blank object and Notification.permission is undefined. This happens in both SharePoint 2010 and 2013.
Anyone experienced this before?
This is expected behaviour since you overwrite the Notification object with your own code.
As soon as you've run var Notification = new Notification("This is a test"); you've overwritten the native Notification function code with an instance of the Notification.
You should instead write something like (notice the lower case n)
if (Notification.permission === "granted") {
var notification = new Notification("This is a test");
}
The requestPermission function is declared in the Notification prototype, which is a property of it's constructor function but not the instance, thus you can never call requestPermission on the returned object from new Notification(...).

Categories

Resources