首先, 查看当前网站有通知权限 google浏览器为例 隐私和安全 通知如果是允许或者是询问状态 就跳过此步(询问状态需要用户确认)
如果通知选项是灰色 无法选中(原因网站不受信任是http),需要在Experiments里设置
设置步骤Chrome地址栏输入:chrome://flags/#unsafely-treat-insecure-origin-as-secure
找到图下 搜索Insecure origins treated as secure 把不安全的视为安全 填入有通知需求的地址(http://ip+端口)多个地址用英文逗号隔开,保存 就配置好了。
JS实现网页消息通知(电脑桌面右下角提示弹框)
<!DOCTYPE html>
<html>
<head>
<title>我的基本HTML页面</title>
</head>
<body>
<button onclick="showNotification()">显示通知</button>
<script type="text/javascript" th:inline="javascript">
function showNotification(){
if (Notification.permission === 'granted') {
// 如果已经获得权限,可以直接发送通知
sendNotification();
} else if (Notification.permission !== 'denied') {
// 如果用户还未做出选择,则请求权限
Notification.requestPermission().then(function (permission) {
// 回调函数会在用户做出选择后被调用
if (permission === 'granted') {
// 用户允许显示通知
sendNotification();
}
});
}
function sendNotification() {
// 发送通知的代码
const notification = new Notification('Hi there!');
}
}
</script>
</body>
</html>
运行效果: