JavaScript 通知

摘要:在本教程中,您将学习如何使用 JavaScript 通知 API 向用户显示桌面通知。

通知 API 允许您使用 JavaScript 向用户显示桌面通知。

通知权限

由于通知 API 很容易被滥用,它默认情况下严格执行两项安全功能

  • 首先,用户必须明确同意在每个来源的基础上接收通知。
  • 其次,只有在安全上下文中(HTTPS)运行的代码才能发送通知。

当您向用户请求通知权限时,他们可能会同意或拒绝。

如果用户明确拒绝,浏览器将记住该选择。并且您没有第二次机会再次请求权限。

如果用户不同意或拒绝,即他们忽略它,您可以再次发送通知权限请求。

要请求通知权限,您使用 Notification 全局对象。此对象具有 requestPermission() 方法,该方法返回一个 Promise,当用户在权限对话框上采取操作时,该方法将解析

let permission = await Notification.requestPermission();Code language: JavaScript (javascript)

权限可以是以下字符串之一:'granted''denied''default'

  • 'granted' – 用户同意接收通知。
  • 'denied' – 用户拒绝接收通知。
  • 'default' – 用户选择未知,浏览器将像值是 'denied' 一样行事。

显示和隐藏通知

要创建通知,您使用 Notification 构造函数。以下创建了一个带有标题的简单通知

const greeting = new Notification('Hi, How are you?');Code language: JavaScript (javascript)

通知可以通过第二个 options 参数进行高度自定义。

例如,以下创建并显示一个带有正文文本和图标的通知

const greeting = new Notification('Hi, How are you?',{
  body: 'Have a good day',
  icon: './img/goodday.png'
});Code language: JavaScript (javascript)

要关闭通知,您调用 Notification 构造函数返回的 Notification 对象的 close() 方法

greeting.close();Code language: CSS (css)

要经过一段时间后关闭通知,您使用 setTimeout() 函数。例如,以下显示了如何关闭 greeting 通知 10 秒后

setTimeout(() => greenting.close(), 10*1000);Code language: JavaScript (javascript)

通知事件

Notification 对象为您提供以下事件

  • show – 通知显示时触发。
  • click – 点击通知时触发。
  • close – 通过 close() 方法关闭或关闭通知时触发。
  • error – 发生阻止通知显示的错误时触发。

要处理这些事件,您使用 Notification 对象的 addEventListener() 方法。

以下示例在点击通知时导航到 URL https://tutorial.javascript.ac.cn/

// create a notification object
const greeting = new Notification('Hi, How are you?',{
  body: 'Have a good day',
  icon: './img/goodday.png'
});

// navigate to the https://tutorial.javascript.ac.cn/ on click
greeting.addEventListener('click', function(){
    window.open('https://tutorial.javascript.ac.cn/web-apis/javascript-notification/');
});Code language: JavaScript (javascript)

除了使用 addEventListener() 之外,您还可以将事件处理程序分配给 Notification 对象的 onclick 属性。例如

greeting.onclick = () => window.open('https://tutorial.javascript.ac.cn/web-apis/javascript-notification/');Code language: JavaScript (javascript)

Notification 对象具有 onshowonclickoncloseonerror,分别对应于这些事件。

JavaScript 通知 API 示例

在本示例中,我们将构建 一个向用户显示桌面通知的简单 Web 应用程序。

创建项目结构

首先,创建一个名为 notification 的新文件夹,并在 notification 文件夹中创建三个子文件夹 jscssimg

其次,在 css 文件夹中创建 style.css,在 js 文件夹中创建 app.js,并在 notification 文件夹中创建 index.html

第三,下载以下图标并将其复制到 img 文件夹中。您将使用它作为通知的图标。

创建 index.html 页面

index.html 页面中,您放置到 style.cssapp.js 文件的链接

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JavaScript Notification API</title>
    <link rel="stylesheet" href="css/style.css">
</head>
<body>
    <div class="container">
        <h1>JavaScript Notification API Demo</h1>
        <div class="error"></div>
    </div>
    <script src="js/app.js"></script>
</body>
</html>Code language: HTML, XML (xml)

index.html 具有一个标题一和一个 <div> 元素,如果未授予通知权限,则该元素将显示错误消息。

创建 app.js 文件

由于您将使用 await 关键字调用 Notification.requestPermission() 方法,因此您需要将 app.js 中的所有代码放在异步 IIFE

(async () => {
   // place js code here
})();Code language: JavaScript (javascript)

首先,定义一个创建和显示通知、在 10 秒后关闭通知以及在点击时打开 URL(https://tutorial.javascript.ac.cn/web-apis/javascript-notification/)的函数

// create and show the notification
const showNotification = () => {
    // create a new notification
    const notification = new Notification('JavaScript Notification API', {
        body: 'This is a JavaScript Notification API demo',
        icon: './img/js.png',
        vibrate: true
    });

    // close the notification after 10 seconds
    setTimeout(() => {
        notification.close();
    }, 10 * 1000);

    // navigate to a URL
    notification.addEventListener('click', () => {
        window.open('https://tutorial.javascript.ac.cn/web-apis/javascript-notification/', '_blank');
    });
}Code language: JavaScript (javascript)

其次,定义另一个函数,如果未授予通知权限,则显示错误消息

// show an error message
const showError = () => {
    const error = document.querySelector('.error');
    error.style.display = 'block';
    error.textContent = 'You blocked the notifications';
}Code language: JavaScript (javascript)

第三,检查是否授予了通知权限。如果用户没有采取任何操作,则请求它。

如果授予了通知权限,则 granted 标志为 true。否则,它为 false。根据 granted 标志的值调用 showNotification()showError() 函数

let granted = false;

if (Notification.permission === 'granted') {
    granted = true;
} else if (Notification.permission !== 'denied') {
    let permission = await Notification.requestPermission();
    granted = permission === 'granted' ? true : false;
}

// show notification or the error message 
granted ? showNotification() : showError();Code language: JavaScript (javascript)

以下是 app.js 文件的完整代码

(async () => {
    // create and show the notification
    const showNotification = () => {
        // create a new notification
        const notification = new Notification('JavaScript Notification API', {
            body: 'This is a JavaScript Notification API demo',
            icon: './img/js.png'
        });

        // close the notification after 10 seconds
        setTimeout(() => {
            notification.close();
        }, 10 * 1000);

        // navigate to a URL when clicked
        notification.addEventListener('click', () => {

            window.open('https://tutorial.javascript.ac.cn/web-apis/javascript-notification/', '_blank');
        });
    }

    // show an error message
    const showError = () => {
        const error = document.querySelector('.error');
        error.style.display = 'block';
        error.textContent = 'You blocked the notifications';
    }

    // check notification permission
    let granted = false;

    if (Notification.permission === 'granted') {
        granted = true;
    } else if (Notification.permission !== 'denied') {
        let permission = await Notification.requestPermission();
        granted = permission === 'granted' ? true : false;
    }

    // show notification or error
    granted ? showNotification() : showError();

})();Code language: JavaScript (javascript)

这里是 演示页面

当您打开页面时,它将请求通知权限

如果您点击允许按钮,您将在桌面上看到以下通知

它将在 10 秒后关闭。如果您点击通知,它将打开 URL https://tutorial.javascript.ac.cn/web-apis/javascript-notification/

总结

  • JavaScript 通知 API 允许您向用户显示桌面通知。
  • 通知必须由用户在每个来源的基础上明确授予,并且只能由在安全上下文中(https)执行的代码触发。
  • 使用 Notification 构造函数创建和显示通知。
  • 使用 Notification 事件使通知更具交互性。
本教程是否有帮助?