我正在尝试创建一个网站,在发生某些事件时显示通知。我查过the MDN page for Notifications我编写了一个在 Firefox Developer Edition 58.0b7 中运行的示例,但在 Edge 40.15063.674.0 和 Chrome 62.0.3202.94(在 Windows 10 中)中出现奇怪的行为。
这是一个最小完整的可验证示例:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>test</title>
</head>
<body>
<script>
function notify(str) {
if(!("Notification" in window) || Notification.permission === "deneided") {
return alert(str);
}
if (Notification.permission === "granted") {
return new Notification("TITLE", {body: str});
}
Notification.requestPermission().then(perm => {
console.log("request result", perm);
console.log("Notification.permission", Notification.permission);
if (perm === "granted") {
return new Notification("TITLE", {body: str});
}
});
}
notify("test");
</script>
</body>
</html>
将该代码保存在计算机中的文件中,然后使用浏览器打开它。
- 在 Firefox 中,如果您在每次询问时授予权限,它就会起作用并显示通知。
- 在 Chrome 中,如果您授予权限,您可以在控制台中看到权限请求返回
"granted"
但是Notification.permission
仍然是“默认”并且不显示通知。运行notify
再次出现另一个对话框,询问显示通知的权限。 - 在 Edge 中,授予权限后,
Notification.permission
是granted
,但尝试创建新通知会导致UnknownError
.
为什么代码可以在 Firefox 中运行,但不能在 Edge 或 Chrome 中运行?我怎样才能让它至少在 Chrome 中工作(希望在 Edge 中)?
最佳答案
您可以按照他们在 MDN notification API Docs 中提供的示例进行操作在“替代示例:在页面加载时运行”下,您可以以更少的开销实现显示通知。
使用本地文件尝试下面的代码(此处的代码片段将拒绝通知尝试)
在 Chrome 中,刷新页面后您将看到 Notification.permission
变量已更新。
Notification.requestPermission().then(function(result) {
console.log(result);
});
document.querySelector('#notifyButton').addEventListener('click', showNotification)
function showNotification(){
console.log('Clicked!!')
var options = {
body: 'this is the body!'
}
var n = new Notification('this is the title', options);
}
<input id="notifyButton" type="button" name="notify" value="click for notification">
关于javascript - 如何跨浏览器显示通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47540094/