我是服务人员和推送通知的新手,所以我正在尝试这个测试项目,以使用服务人员和node.js创建推送通知。尝试注册推送时,控制台中始终出现此DOMException错误。
这是我的代码
const publicVapidKey =
"BA6iGR7K3KfA_xn9XZTDqKMjUZcA6o8IsnDtnkvxtmkg4GwuTCsqNU-8YUoEIkfYCpuF7PraFKVI0zvNfNsPjy0";
//check for service worker
if ("serviceWorker" in navigator && "PushManager" in window) {
console.log("Service Worker and Push is supported");
send().catch(err => console.error(err));
}
// Register the service worker
async function send() {
console.log("Registering Service Worker...");
const register = await navigator.serviceWorker.register("/worker.js", {
scope: "/"
});
console.log("Service Worker Registered...");
//Register push
console.log("Registering Push...");
const subscription = await register.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: urlBase64ToUint8Array(publicVapidKey)
});
console.log("Push Registered...");
//send push notification
console.log("Sending Push... ");
await fetch("/subscribe", {
method: "POST",
body: JSON.stringify(subscription),
headers: {
"content-type": "application/json"
}
});
console.log("Push Sent...");
}
//
function urlBase64ToUint8Array(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;
}
答案 0 :(得分:1)
哦,事实证明我在chrome浏览器设置中关闭了通知。我现在打开它,一切正常