我已经集成了PushPad,并设法使它在静态Push中工作,现在我想将它与一些PHP和Javascript函数结合起来,使其具有动态。这是我的代码:
<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"-alert。然后,Chrome要求我接受推送通知。我单击“允许”,然后弹出“订阅”警报。
如果我现在刷新站点,所有内容都会重复到“订阅”-alert(但我不再被要求允许Chrome的推送通知)。我原以为“已经订阅”的警报应该出现,因为我以前订阅过,但它没有。
如果有人能帮忙,我会很感激的:-)
发布于 2016-05-25 08:43:52
问题是status返回当前用户(uid)的订阅状态。您只将uid设置为订阅,状态不知道它。
这就是您的代码中发生的情况:
status检查uid = null是否有订阅(因为还没有设置实际的用户id )。null的订阅解决方案是在AJAX成功回调中移动所有Pushpad代码。你的顺序如下:
顺便问一下,为什么要使用AJAX回调来获取uid?如果用户在呈现包含Pushpad代码的页面时登录到您的网站上,您可能已经知道uid (例如用户电子邮件或数据库中用户的id )。你可以做一些像pushpad('uid', '<?= $uid ?>', '<?= $uid_signature ?>');这样的事情
https://stackoverflow.com/questions/37425297
复制相似问题