How to verify if a check box is checked? - javascript

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).

Related

Pushing a browser notification when a threshold is met

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

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 add a callback to a function in the moment when it is triggered?

I would like to add a callback to this function: Notification.requestPermission(). The problem is I don't know when exactly it (that function) will be triggered, hence I think I have to bind the browser notification permission box on click or something like that, to achieve that everytime user clicks on "ALLOW", "BLOCK" or "X"(close) the javascript file finds out what button was clicked on and does something like this:
if (result === 'denied')
{
console.log('Permission wasn\'t granted. Allow a retry.');
return;
}
if (result === 'default')
{
console.log('The permission request was dismissed.');
return;
}
if (result === 'accepted')
{
console.log('The permission request was accepted.');
return;
}
My problem is I don't know how it can be binded to that browser notification permission box like the one below ↓
I do not want to call the permission prompt i.e. Notification.requestPermission() function. I just want to detect when Permission was changed and do something with that result.
You generally request for permission on page load.
With jquery you can do something like
jQuery(document).ready(function() {
if (!("Notification" in window)) {
console.log("This browser does not support desktop notification");
} else if (Notification.permission !== 'denied') {
Notification.requestPermission(function(permission) {
if (!('permission' in Notification)) {
Notification.permission = permission;
}
});
}
});
soo, i'm not entirely sure, if i understand you right, but i don't think you need to bind your stuff to the notification permission box.
According to MDN there are two ways to do this: either use promises:
Notification.requestPermission().then(function(permission) { ... });
or the callback
Notification.requestPermission(callback);
I think it's more obvious for the promise how to get the value of the permission, but if you'd use a "normal" callback you could wrap your code into a function and check for the permission parameter:
function doStuff(result){
if (result === 'denied')
{
console.log('Permission wasn\'t granted. Allow a retry.');
return;
}
if (result === 'default')
{
console.log('The permission request was dismissed.');
return;
}
if (result === 'accepted')
{
console.log('The permission request was accepted.');
return;
}
}
and then call:
Notification.requestPermission(doStuff(permission));
then maybe save the result in a global var ( i don't know what you want to do with it, so yeah)
I was searching for the same thing and I found this answer here:
How to listen for web notification permission change
I think this is what you are looking for. It is working for me.

(Chrome Extensions) How to test onUpdateAvailable

Is there a way to onUpdateAvailable manually (without using code)?
How can I trigger the onUpdateAvailable event without using code?
Because I also need to test my code in a "non-technical / non-developer" way.
Thanks.
Add this listener to your extension:
chrome.runtime.onUpdateAvailable.addListener(function(){
alert("update available!");
})
Have someone manually use your extension, and then you should issue an update while they are using it. This manual test just checks if the alert gets triggered. If you see the alert, or something visible from a "user's perspective", then the test passes.
The only way to manually/organically trigger onUpdateAvailable is actually having an update available and publishing that update (note the extension must be published as well).
Lastly, you should now manually request an update from the extensions page in Developer mode (Thanks #Xan for the tip)
Another way to request an update check is with a function bound to a button that a user can click.
Request an update check as explained in this answer by clicking a button:
HTML
<button>Test onUpdateAvailable</button>
JavaScript
document.addEventListener('DOMContentLoaded', function () {
document.querySelector('button').addEventListener('click', onUpdateAvailable);
});
// request an update
function test_onUpdateAvailable() {
chrome.runtime.requestUpdateCheck(function(status) {
if (status == "update_available") {
console.log("update pending... expecting alert!");
} else if (status == "no_update... not expecting alert!") {
console.log("no update found");
} else if (status == "throttled") {
console.log("Oops, I'm asking too frequently - I need to back off.");
}
});
}
Documentation for onUpdateAvailable
Documentation for requestUpdateCheck

Problem with redirect after FB.Connect.showPermissionDialog

I'm building a facebook connect app to publish content to user's streams. In order to do that, I need to get extended publish_stream permission from the users. I'm using the function code to do so.
Check connection status
<input type="button" onclick="statusSubmit('Permission to publish : ');" value="Check connection status" />
<script type="text/javascript">
function statusSubmit(status)
{
facebook_prompt_permission('publish_stream', function(accepted)
{
if(accepted) {
// User (already) has permission
alert(status + 'already granted');
}
else
{
// User does not have permission
alert(status + ' not granted');
}
});
}
function facebook_prompt_permission(permission, callbackFunc)
{
// Check if user has permission, if not invoke dialog.
FB.ensureInit(function() {
FB.Connect.requireSession(function(){
//check is user already granted for this permission or not
FB.Facebook.apiClient.users_hasAppPermission(permission,
function(result) {
// prompt offline permission
if (result == 0) {
// render the permission dialog
FB.Connect.showPermissionDialog(permission,
function(result){
if (null == result)
alert('no permissons granted');
else
alert('permissions ' + result);
}, true, null);
} else {
// permission already granted.
callbackFunc(true);
}
});
});
});
}
</script>
After the permissions dialog is displayed and the user grants the permissions, there is a redirect my current page on my local development machine. I cannot seem to control this redirect behaviour through my settings. I have tried changing the "Post-Authorize Callback URL" to a publicly visible page, but it does not get called. Is there something I'm missing? I would like to either
Get the post-authorize callback URL to something that works OR
Even better if there is no redirection after the user grants
permissions. This option would be the best.
Thank you for any suggestions.
abronte, Thank you for your suggestion. I actually figured out that the path to xd_receiver.htm was incorrect, which was causing all the weird behavior. When I corrected that, things were OK. But the FB Javascript API is very flaky, we decided not to use it as the behavior is erratic. We will be switching to a server based solution in the future.
I believe that the post-authorize callback url that is set in the application settings only deals with within facebook canvas sort of stuff. What url is called after you authorize the app in facebook.
What I think the best solution is (and this is what i do) is to manually redirect the user after the extended permissions prompt is completed.
window.location = '/path/to/something';

Categories

Resources