Search code examples
javascriptfunctionpush-notificationnotificationsweb-push

Use Notification.requestPermission on different browser versions as per it's implementation


I have a problem where a function has its implementation changed in newer browsers. I want to call the function accordingly as per the implementation.

Notification.requestPermission().then(function (permission) {...})

This was called previously like,

Notification.requestPermission(callback);

I was calling the initial way and so in older browsers it is breaking as the promise is not returned in their implementation.


Solution

  • Taking a shot at this. It seems like you need to have a function fired conditionally with a flag.

    // Outer function to prevent scope pollution
    (function(){
        function thingThatINeed() {}
        // Flag to keep track of whether it is called.
        var isCalled = false;
        function conditionalCall(){
           if(!isCalled) {
               // if the conditionalCall function is called more than once, the 
               // needed function will still only be called once.
               thingThatINeed();
               isCalled = true;
           }
        }
        // Call requestPermission with the deprecated form
        var promise = Notification.requestPermission(conditionalCall);
    
        // if a promise is returned, then use the promise.
        if(promise){
            promise.then(conditionalCall);
        }
    }());