javascript - 如何跨浏览器显示通知

标签 javascript google-chrome firefox notifications microsoft-edge

我正在尝试创建一个网站,在发生某些事件时显示通知。我查过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.permissiongranted ,但尝试创建新通知会导致 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/

相关文章:

javascript - JavaScript/Chrome 如何在本地执行跨域请求?

google-chrome - Google Chrome 设备框架在打开时不可见

Angular 4 @HostListener Window 滚动事件奇怪地在 Firefox 中不起作用

javascript - 通过 AJAX 发布 Canvas blob : prevent/delete local cache

javascript - 如何将输入绑定(bind)到 observableArray 中的可观察对象?

firefox - 浏览器调试 - 如何让浏览器重新加载服务器的响应而不重新请求它?

html - 如何修复 <select> 下拉菜单水平晃动(仅限 Firefox)?

javascript - 使用 Express 响应服务器端渲染 - 客户端校验和和样式警告

javascript - 如何创建新的 Angular 服务实例?

html - Firefox不会播放此html片段,但Chrome和Opera会提示什么吗?