django-webpush icon indicating copy to clipboard operation
django-webpush copied to clipboard

Subscribing - consider existing subscription

Open arogachev opened this issue 8 years ago • 2 comments

When page initially loaded, subscribe button is shown regardless of user already subscribed or not, This is not user friendly interface.

At least we need to check if user already subscribed and show some information about that (for example display "Unsubscribe" button instead).

arogachev avatar Oct 10 '16 06:10 arogachev

@arogachev So the thing is, user can subscribe from multiple browser. We do not show the message if the user already subscribed from the the same browser. Does it make sense?

safwanrahman avatar Sep 22 '18 00:09 safwanrahman

I found a solution for that. You need to inject a array of endpoint on your view

    pushs = PushInformation.objects.filter(user=request.user).all()

    endpoints=[]

    for push in pushs:

        endpoint = push.subscription.endpoint
        endpoints.append(endpoint)
    end= json.dumps({"point":endpoints})
    if pushs:
        pushactif=1
    else:
        pushactif=0
    return render(request, 'mytemplate.html', { 'pushactif':pushactif, 'end':end})

After that you can write a little code in js to check if the end point of our registration match any of endpoint found on server.

    $(function () {
        var active = {{ pushactif }};
        var end = `{{ end|safe }}`;
        var endpoints = JSON.parse(end);
        var serviceWorker = document.querySelector('meta[name="service-worker-js"]').content;
        navigator.serviceWorker.register(serviceWorker)
            .then(
                function(reg) {
                    registration = reg;
                    var navpoint;
                    registration.pushManager.getSubscription().then(function (nav) {
                        navpoint=  nav.endpoint;
                        let ok =0;
                        if (active === 1){
                            for (let i=0; i<endpoints.point.length; i++){
                                if (endpoints.point[i]===navpoint){
                                    ok=1;
                                }
                            }
                        }
                        if (ok===1){
                            subBtn.textContent = 'Unsubscribe to Push Messaging';
                            subBtn.disabled = false;
                            isPushEnabled = true;
                        }
                    })
                }
            );`

elineda avatar Sep 09 '19 12:09 elineda