Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if notifications is already allowed by user in google chrome?

I have a modal that pops up first asking if the user wants to receive special offers, if they click yes, then I pull in the code for push notifications so that they can allow notifications. If they already allowed notifications I don't want the modal to pop up. I am looking for a way to check if notifications has already been allowed by the user, using google chrome.

like image 594
cmac Avatar asked Jun 22 '16 16:06

cmac


People also ask

How do I check notifications on Chrome?

Open the Chrome app on your device. Go to the right side of the address bar and click on Settings. Tap on Site Settings and click on Notifications. Go to the top to turn the settings, “on or off.”


2 Answers

Check the permission property of the Notification object:

if (Notification.permission !== "granted") {
    // ask for permission
like image 148
Denys Séguret Avatar answered Sep 16 '22 22:09

Denys Séguret


Alongside Notification.permission as answered by Denys Séguret there is the newer, less well-supported but more general Permissions API.

Here's a quick usage example, based on the one from MDN:

function handlePermission() {
    return navigator.permissions
            .query({name:'notifications'})
            .then(permissionQuery)
            .catch(permissionError);
}

function permissionQuery(result) {
    console.debug({result});
    var newPrompt;

    if (result.state == 'granted') {
        // notifications allowed, go wild

    } else if (result.state == 'prompt') {
        // we can ask the user
        newPrompt = Notification.requestPermission();

    } else if (result.state == 'denied') {
        // notifications were disabled
    }

    result.onchange = () => console.debug({updatedPermission: result});

    return newPrompt || result;
}

////

handlePermission();
like image 43
Robert K. Bell Avatar answered Sep 17 '22 22:09

Robert K. Bell