【发布时间】:2016-09-27 11:51:39
【问题描述】:
我关注了tutorial,使用 GCM 在 Google Chrome 上进行推送通知。我的问题是我无法完成操作!我不知道为什么。
在订阅函数中,它会在尝试执行时中断该函数
navigator.serviceWorker.ready.then(function(serviceWorkerRegistration) {
serviceWorkerRegistration.pushManager.subscribe()
.then(function(subscription) {
// ...
};
});
没有控制台错误,没有控制台警告,也没有进入catch!这是我所做的:
function subscribe() {
var pushButton = document.querySelector('.js-push-button');
pushButton.disabled = true;
navigator.serviceWorker.ready.then(function(serviceWorkerRegistration) {
serviceWorkerRegistration.pushManager.subscribe()
.then(function(subscription) {
// The subscription was successful
isPushEnabled = true;
pushButton.textContent = 'Disable Push Messages';
pushButton.disabled = false;
console.log("sending sub");
sendSubscriptionToServer(subscription);
// TODO: Send the subscription.endpoint to your server
// and save it to send a push message at a later date
return sendSubscriptionToServer(subscription);
})
.catch(function(e) {
if (Notification.permission === 'denied') {
// The user denied the notification permission which
// means we failed to subscribe and the user will need
// to manually change the notification permission to
// subscribe to push messages
console.warn('Permission for Notifications was denied');
pushButton.disabled = true;
} else {
// A problem occurred with the subscription; common reasons
// include network errors, and lacking gcm_sender_id and/or
// gcm_user_visible_only in the manifest.
console.error('Unable to subscribe to push.', e);
pushButton.disabled = false;
pushButton.textContent = 'Enable Push Messages';
}
});
});
}
【问题讨论】:
-
请先尝试注册您的 Service Worker,因为这是使用它的第一步。这个GitHub post 可能有助于更好地了解服务人员。
标签: javascript push-notification google-cloud-messaging