How to: Show the Push Notification Permission Prompt

Posted on 16. September 2022 by Jan Bunk


The features described on this page require a plan that includes push notifications.

For quite a while now iOS users had to be asked for permission before you could send them push notifications. Since Android 13, this also applies to Android users.

By default, apps created with webtoapp.design automatically ask for permission on the third launch of the app. If you want to customize this behaviour for your app, you can use the following JavaScript functions.

Using the JavaScript Functions

You might want to check out the executeWhenAppReady() function of our app helper script. It ensures that your website doesn't try to interact with the app before it's ready or when your website is loaded using a regular browser (ReferenceError, function is not defined).

notificationPermissionsGranted

Use this function when you want to check if the user has granted push notification permissions.


<script>
    try {
        // returns true or false
        let granted = (await notificationPermissionsGranted())["granted"];
    }
    catch (e) {
        // Can occur if:
        // - the app couldn't connect to the native code. Should be very unlikely.
        // - the app couldn't get the push notification permission status. Should be very unlikely.
        // - push notifications are not included in your current plan
        console.log(e);
    }
</script>
    

requestNotificationPermissions

Use this function when you want to show the push notification permission prompt.

The function takes one boolean parameter which determines whether the settings should be opened in case the regular permission prompt was previously rejected. Here are screenshots of the settings pages that would be opened on Android and iOS:

The Android app info screen where notifications can be enabled manually.
The Android app info screen where notifications can be enabled manually.
A screenshot of the iOS notification settings.
A screenshot of the iOS notification settings.

Because this behaviour could be confusing for users, you should only set the parameter to true if the user explicitly indicated they want to enable push notifications. If the parameter is set to false, the function can be a no-op in case previous permission requests were not granted.


<script>
    try {
        let openSettingsIfNecessary = false;

        // doesn't return anything
        await requestNotificationPermissions(openSettingsIfNecessary);
    }
    catch (e) {
        // Can occur if:
        // - the app couldn't connect to the native code. Should be very unlikely.
        // - the app couldn't ask for push notification permissions. Should be very unlikely.
        // - push notifications are not included in your current plan
        console.log(e);
    }
</script>