2

我已经集成了 PushPad 并设法让它为静态推送工作。现在我想将它与一些 PHP 和 Javascript-Functions 结合起来使其动态化。这是我的代码:

<script>
    (function(p,u,s,h,x){p.pushpad=p.pushpad||function(){(p.pushpad.q=p.pushpad.q||[]).push(arguments)};h=u.getElementsByTagName('head')[0];x=u.createElement('script');x.async=1;x.src=s;h.appendChild(x);})(window,document,'https://pushpad.xyz/pushpad.js');

    //Install Pushpad
    pushpad('init', myprojectnumber);
    alert("Pushpad initialised");
    //Check subscribe-status
    pushpad('status', function (isSubscribed, tags){
        //User is already subscribed
        if (isSubscribed){
            alert("Already subscribed");
        //User has not subscribed
        }else{
            alert("Not subscribed");
            //Check in database if this logged-in-user has already subscribed with 5 different devices, if not generate UID and UID_SIGNATURE
            var username = $('#username_show').html();

            alert('Username: ' + username);
            $.ajax
            ({                                        
                type: "POST",
                data: {username: username},
                dataType: "json",
                url: "setNotifications.php",
                cache: false,
                success: function(data)
                {
                    alert("Ajax successfull. UID generated.");

                    if (data.uid != 0){
                        //Set UID and UID-SIGNATURE
                        pushpad('uid', data.uid, data.uid_signature);
                        alert('UID:' + data.uid);
                        //Subscribe
                        pushpad('subscribe', function(isSubscribed){
                            if (isSubscribed){
                                alert("Subscribed");
                            }else{
                                alert("Notifications blocked");
                            }

                        });
                    //Already 5 devices subscribed
                    }else{
                        alert("Already 5 devices");
                    }
                },
                error: function()
                {
                    alert('Error');
                }
            });
        }
    });
</script>

乍一看,一切正常。如果我第一次访问该站点,所有警报都会弹出,直到“UID”警报。然后我被 Chrome 要求接受推送通知。我单击允许,然后弹出“已订阅”警报。

如果我现在刷新网站,一切都会重复到“订阅”警报(但我不再被要求允许 Chrome 推送通知)。我原以为应该显示“已订阅”警报,因为我以前订阅过,但没有。

如果有人可以提供帮助将不胜感激:-)

4

1 回答 1

1

问题是返回当前用户 (uid)status的订阅状态。您只为订阅设置了 uid,而状态并不知道。

这是您的代码中发生的情况:

  1. 用户实际上订阅了推送通知
  2. 你刷新页面
  3. status检查是否有订阅 uid = null(不是实际用户 id,因为尚未设置!)
  4. 它返回 false 因为没有订阅 uid =null
  5. 再次触发订阅流程

解决方案是将所有 Pushpad 代码移动到 AJAX 成功回调中。所以你下面的顺序:

  1. 推板('初始化')
  2. 你的 ajax 回调
  3. 成功后,您使用 pushpad('uid') 设置 uid
  4. 推板('状态')
  5. 在 pushpad('status') 回调中使用 pushpad('subscribe')

顺便说一句,您为什么使用 AJAX 回调来获取 uid?如果用户在您呈现包含 Pushpad 代码的页面时登录您的网站,您可能已经知道 uid(例如,用户电子邮件或数据库中用户的 id)。你可以做类似的事情pushpad('uid', '<?= $uid ?>', '<?= $uid_signature ?>');

于 2016-05-25T08:43:52.383 回答