Mettre en œuvre la notification de notification

Comme le montre cet effet

 Peut être implémenté à l'aide de l'API de notification

spectacle de code comme ci-dessous

Remarque : Assurez-vous d'utiliser le serveur pour ouvrir. Sinon, il ne s'affichera pas. Vscode peut installer le serveur de plug-in Live Serve pour ouvrir

<!DOCTYPE html>
<html lang="zh">

<head>
	<meta charset="UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Document</title>
</head>

<body>
	<button>点击弹出提示</button>
	<script>
		document.querySelector('button').addEventListener('click', function () {
			// 检查浏览器是否支持 Notification API
			if ("Notification" in window) {
				// 请求用户授权显示通知
				Notification.requestPermission().then(function (permission) {
					// denied——用户拒绝显示通知
					// granted——用户接受显示通知
					// default——用户选择是未知的,因此浏览器的行为类似于值是 denied
					if (permission === "granted") {
						// 创建通知
						var notification = new Notification("这是一个消息通知", {
							// dir:文字方向,可能的值为auto、ltr(从左到右)和rtl(从右到左),一般是继承浏览器的设置
							dir: "auto",
							// body:通知的内容  注意:body 属性是必须的,否则通知无法显示
							body: "这里是通知的内容",
							// tag:通知的ID,格式为字符串。一组相同tag的通知,不会同时显示,只会在用户关闭前一个通知后,在原位置显示
							tag: "my-notification",
							// 通知的图片
							image: './imgs/R-D.jpg'
							// 可选,通知的图标
							// icon: ""
						})

						// 通知显示给用户时触发的回调函数
						notification.onshow = function () {
							console.log("显示给用户时")
						}
						// 点击通知时的回调函数
						notification.onclick = function () {
							console.log("用户点击了通知")
						}
						// 关闭通知时的回调函数
						notification.onclose = function () {
							console.log("用户关闭了通知")
						}
						// 通知出错时的回调函数
						notification.onerror = function () {
							console.log("通知出错时触发(大多数发生在通知无法正确显示时)")
						}
					}
				})
			} else {
				alert("浏览器不支持 Notification API")
			}
		})
	</script>
</body>

</html>

Guess you like

Origin blog.csdn.net/qq_52845451/article/details/132171218