Javascript 在使用通知API时,如何向通知添加URL?
通过在页面底部添加以下脚本,我在标准index.html文件中创建了一个简单的通知。但是,我的目标是在通知中添加URL,这样当用户单击通知时,他们将被带到特定的URL(window.open)。我知道这可以做到,就像在谷歌上搜索答案一样,许多网站都有通知,当点击时会导航到不同的页面或网站。尽管如此,我还没有找到一个解决办法,我可以得到工作。欢迎任何帮助Javascript 在使用通知API时,如何向通知添加URL?,javascript,api,notifications,Javascript,Api,Notifications,通过在页面底部添加以下脚本,我在标准index.html文件中创建了一个简单的通知。但是,我的目标是在通知中添加URL,这样当用户单击通知时,他们将被带到特定的URL(window.open)。我知道这可以做到,就像在谷歌上搜索答案一样,许多网站都有通知,当点击时会导航到不同的页面或网站。尽管如此,我还没有找到一个解决办法,我可以得到工作。欢迎任何帮助 Notification.requestPermission(); Notification.requestPermission((pe
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
}
你错过了一条对这项工作非常重要的线路。使用
通知
构造函数定义通知,在其中输入标题
和选项
变量
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);
});
}
您当前的代码将抛出一些与原始问题无关的错误。请确保在代码中修复这些问题。@EmielZuurbier感谢您的见解。我的chrome控制台中报告的唯一错误是与通知相关的错误(未定义)。不知道怎么修。谢谢你的帮助。我可以看到如何声明一个新常量。我想这是我遗漏的东西,或者是我用来形成代码的代码片段中没有包含的东西。查看此变量,所有此类通知似乎都需要此行。这就是为什么当它丢失时,您报告了一个错误,与最初的帮助请求无关。再次感谢,您的回答让我更了解了一点:)