因此,我正在练习Web通知,并且碰到了本教程https://developers.google.com/web/fundamentals/codelabs/push-notifications/,虽然我不太了解此处的所有代码,但是我试图通过一个接一个地尝试来实现,但是我遇到了一个问题如何通过按钮推送Web通知?
这些是我的代码:
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Push Codelab</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="https://code.getmdl.io/1.2.1/material.indigo-pink.min.css">
<script defer src="https://code.getmdl.io/1.2.1/material.min.js"></script>
<link rel="stylesheet" href="styles/index.css">
</head>
<body>
<header>
<h1>Push Codelab</h1>
</header>
<main>
<p>Welcome to the push messaging codelab. The button below needs to be
fixed to support subscribing to push.</p>
<p>
<button disabled class="js-push-btn mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect">
Enable Push Messaging
</button>
<button class="js-push-btn mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect" id="notify">
Enable Push Messaging
</button>
</p>
<section class="subscription-details js-subscription-details is-invisible">
<p>Once you've subscribed your user, you'd send their subscription to your
server to store in a database so that when you want to send a message
you can lookup the subscription and send a message to it.</p>
<p>To simplify things for this code lab copy the following details
into the <a href="https://web-push-codelab.glitch.me//">Push Companion
Site</a> and it'll send a push message for you, using the application
server keys on the site - so make sure they match.</p>
<pre><code class="js-subscription-json"></code></pre>
</section>
</main>
<script src="scripts/main.js"></script>
<script src="https://code.getmdl.io/1.2.1/material.min.js"></script>
</body>
</html>
main.js
'use strict';
const applicationServerPublicKey = 'BMpQ-7s56rTLKF7lR6wWQP9kKCbP3Q7Kidi96lHvREfmVV1mFtmSo08g_FuJ9vJkyGefboFo1Nj0JPlR2er9NLM';
const pushButton = document.querySelector('.js-push-btn');
const notifyButton = document.querySelector('#notify');
let isSubscribed = false;
let swRegistration = null;
function urlB64ToUint8Array(base64String) {
const padding = '='.repeat((4 - base64String.length % 4) % 4);
const base64 = (base64String + padding)
.replace(/\-/g, '+')
.replace(/_/g, '/');
const rawData = window.atob(base64);
const outputArray = new Uint8Array(rawData.length);
for (let i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i);
}
return outputArray;
}
if ('serviceWorker' in navigator && 'PushManager' in window) {
console.log('Service Worker and Push is supported');
navigator.serviceWorker.register('sw.js')
.then(function(swReg) {
console.log('Service Worker is registered', swReg);
swRegistration = swReg;
})
.catch(function(error) {
console.error('Service Worker Error', error);
});
} else {
console.warn('Push messaging is not supported');
pushButton.textContent = 'Push Not Supported';
}
function initializeUI() {
// Set the initial subscription value
swRegistration.pushManager.getSubscription()
.then(function(subscription) {
isSubscribed = !(subscription === null);
if (isSubscribed) {
console.log('User IS subscribed.');
} else {
console.log('User is NOT subscribed.');
}
updateBtn();
});
}
function updateBtn() {
if (isSubscribed) {
pushButton.textContent = 'Disable Push Messaging';
} else {
pushButton.textContent = 'Enable Push Messaging';
}
pushButton.disabled = false;
}
navigator.serviceWorker.register('sw.js')
.then(function(swReg) {
console.log('Service Worker is registered', swReg);
swRegistration = swReg;
initializeUI();
})
function initializeUI() {
pushButton.addEventListener('click', function() {
pushButton.disabled = true;
if (isSubscribed) {
// TODO: Unsubscribe user
} else {
subscribeUser();
}
});
// Set the initial subscription value
swRegistration.pushManager.getSubscription()
.then(function(subscription) {
isSubscribed = !(subscription === null);
updateSubscriptionOnServer(subscription);
if (isSubscribed) {
console.log('User IS subscribed.');
} else {
console.log('User is NOT subscribed.');
}
updateBtn();
});
}
function subscribeUser() {
const applicationServerKey = urlB64ToUint8Array(applicationServerPublicKey);
swRegistration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: applicationServerKey
})
.then(function(subscription) {
console.log('User is subscribed.');
updateSubscriptionOnServer(subscription);
isSubscribed = true;
updateBtn();
})
.catch(function(err) {
console.log('Failed to subscribe the user: ', err);
updateBtn();
});
}
function updateSubscriptionOnServer(subscription) {
// TODO: Send subscription to application server
const subscriptionJson = document.querySelector('.js-subscription-json');
const subscriptionDetails =
document.querySelector('.js-subscription-details');
if (subscription) {
subscriptionJson.textContent = JSON.stringify(subscription);
subscriptionDetails.classList.remove('is-invisible');
} else {
subscriptionDetails.classList.add('is-invisible');
}
}
function updateBtn() {
if (Notification.permission === 'denied') {
pushButton.textContent = 'Push Messaging Blocked.';
pushButton.disabled = true;
updateSubscriptionOnServer(null);
return;
}
if (isSubscribed) {
pushButton.textContent = 'Disable Push Messaging';
} else {
pushButton.textContent = 'Enable Push Messaging';
}
pushButton.disabled = false;
}
pushButton.addEventListener('click', function() {
pushButton.disabled = true;
if (isSubscribed) {
unsubscribeUser();
} else {
subscribeUser();
}
});
function unsubscribeUser() {
swRegistration.pushManager.getSubscription()
.then(function(subscription) {
if (subscription) {
return subscription.unsubscribe();
}
})
.catch(function(error) {
console.log('Error unsubscribing', error);
})
.then(function() {
updateSubscriptionOnServer(null);
console.log('User is unsubscribed.');
isSubscribed = false;
updateBtn();
});
}
function unsubscribeUser() {
swRegistration.pushManager.getSubscription()
.then(function(subscription) {
if (subscription) {
return subscription.unsubscribe();
}
})
.catch(function(error) {
console.log('Error unsubscribing', error);
})
.then(function() {
updateSubscriptionOnServer(null);
console.log('User is unsubscribed.');
isSubscribed = false;
updateBtn();
});
}
function pushNotification(){
swRegistration.addEventListener('push', function (event) {
console.log('[Service Worker] Push Received.');
console.log(`[Service Worker] Push had this data: "${event.data.text()}"`);
const title = 'Push Codelab';
const options = {
body: 'Yay it works.',
icon: 'images/icon.png',
badge: 'images/badge.png'
};
event.waitUntil(swRegistration.registration.showNotification(title, options));
});
swRegistration.addEventListener('notificationclick', function (event) {
console.log('[Service Worker] Notification click Received.');
event.notification.close();
event.waitUntil(
clients.openWindow('https://developers.google.com/web/')
);
});
}
notifyButton.addEventListener('click', function() {
alert("alert");
pushNotification();
})
sw.js
'use strict';
self.addEventListener('push', function (event) {
console.log('[Service Worker] Push Received.');
console.log(`[Service Worker] Push had this data: "${event.data.text()}"`);
const title = 'Push Codelab';
const options = {
body: 'Yay it works.',
icon: 'images/icon.png',
badge: 'images/badge.png'
};
event.waitUntil(self.registration.showNotification(title, options));
});
self.addEventListener('notificationclick', function (event) {
console.log('[Service Worker] Notification click Received.');
event.notification.close();
event.waitUntil(
clients.openWindow('https://developers.google.com/web/')
);
});
如您所见,我添加了一个名为 pushNotification(); 的新函数,该函数在单击通知按钮时使用,但不会发送通知。有没有更简单的代码呢?我的大脑已经崩溃了。
当前,我可以通过访问开发人员模式>应用程序>服务工作者来推送通知。但是我想要我创建的按钮。
答案 0 :(得分:1)
我想我已经找到答案了,showNotification是我所需要的,对于任何有相同问题的人,请尝试一下。为我工作。
notifyButton.addEventListener('click', function() {
const title = 'Simple Title';
const options = {
body: 'Simple piece of body text.\nSecond line of body text :)'
};
swRegistration.showNotification(title, options);
})
答案 1 :(得分:0)
通常,此实现应转到服务工作者js文件中,以便向用户显示任何到达的推送,而无需最终用户进行手动干预, 自我注册。 showNotification (...)
self.addEventListener('push', function (event) {
if (!(self.Notification && self.Notification.permission === 'granted')) {
return;
}
var data = {};
if (event.data) {
data = event.data.json();
}
console.log('Notification Received:');
console.log(data);
try {
var title = data.title;
var message = data.message;
var url = data.data.url;
var icon = "images/ns-logo.png";
event.waitUntil(self.registration.showNotification(title, {
body: message,
icon: icon,
badge: icon,
data: url
}));
}
catch (err) {
console.log('Notification Processing Failed:', err);
}
});
答案 2 :(得分:0)
确保您已经注册 sw.js ,并允许 权限 浏览器通知。< / p>
HTML
<button id="ABCD" class="btn btn-block">Notify</button>
您的JS
var btnnotify = document.querySelector('#ABCD');
btnnotify.addEventListener('click', function () {
navigator.serviceWorker.getRegistration().then(sw => {
let options = {
body: "Let's buy some Nendoroid!",
icon: "img/Sukusuku Hakutaku.png",
};
sw.showNotification("I want to buy a Nendoroid!", options);
});
});