我通过将以下脚本添加到页面底部,在标准 index.html 文件中创建了一个简单的通知。但是,我的目标是向通知添加 URL,以便当用户单击通知时,他们将被带到特定的 URL (window.open)。我知道这是可以做到的,因为当在 Google 上搜索答案时,许多网站都会发出通知,单击后会导航到不同的页面或网站。尽管如此,我还没有找到可以工作的解决方案。欢迎任何帮助。
Notification.requestPermission();
Notification.requestPermission((permission) => {
switch (permission) {
case 'granted': {
console.log('Now we can send notifications!');
doNotify();
break;
}
case 'denied': {
console.log('User close the request pop-up!')
}
}
});
function doNotify(){
const title = "Test notification";
const img = "https://via.placeholder.com/600x400";
const text = Lorem ipsum;
const options = {
body: text,
icon: "https://via.placeholder.com/600x400",
data: {
},
vibrate: [200, 100, 200],
tag: "new-product",
image: img,
badge: "https://via.placeholder.com/128x128",
};
notification.onclick = function(event) {
event.preventDefault(); // prevent the browser from focusing the Notification's tab
window.open('http://www.mozilla.org', '_blank');
}
navigator.serviceWorker.ready.then(function(serviceWorker) {
serviceWorker.showNotification(title, options);
});
// setTimeout( n.close.bind(n), 9000); //close notification after 3 seconds
}
最佳答案
您错过了一行对于此操作非常重要的行。使用 Notification
构造函数定义通知,在其中输入 title
和 options
变量。
function doNotify() {
const title = "Test notification";
const img = "https://via.placeholder.com/600x400";
const text = "Lorem ipsum";
const options = {
body: text,
icon: "https://via.placeholder.com/600x400",
data: {},
vibrate: [200, 100, 200],
tag: "new-product",
image: img,
badge: "https://via.placeholder.com/128x128",
};
// Add this line.
const notification = new Notification(title, options);
notification.onclick = function(event) {
event.preventDefault(); // prevent the browser from focusing the Notification's tab
window.open('http://www.mozilla.org', '_blank');
}
navigator.serviceWorker.ready.then(function(serviceWorker) {
serviceWorker.showNotification(title, options);
});
}
关于javascript - 使用通知 API 时如何向通知添加 URL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61169326/