aboutsummaryrefslogtreecommitdiff
path: root/files/zh-cn/web/api/notification/requestpermission/index.html
blob: f49bc4b49419a3efdaaf9111a943b3a3779e5cb6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
---
title: Notification.requestPermission()
slug: Web/API/notification/requestPermission
tags:
  - 通知
translation_of: Web/API/Notification/requestPermission
---
<p>{{APIRef("Web Notifications")}}</p>

<p>{{domxref("Notification")}} 接口的 <strong><code>requestPermission()</code> </strong>方法请求用户当前来源的权限以显示通知。</p>

<h2 id="语法">语法</h2>

<p>最新的规范已将此方法更新为基于promise的语法,工作原理如下:</p>

<pre class="brush: js">Notification.requestPermission().then(function(permission) { ... });</pre>

<p>以前,语法是基于一个简单的回调;此版本现<s style="color: red;">已弃用</s></p>

<pre class="brush: js line-numbers  language-js"><code class="language-js">Notification<span class="punctuation token">.</span><span class="function token">requestPermission</span><span class="punctuation token">(</span>callback<span class="punctuation token">)</span><span class="punctuation token">;</span></code></pre>

<h3 id="参数">参数</h3>

<dl>
 <dt><code>callback</code> {{optional_inline}} {{deprecated_inline("gecko46")}}</dt>
 <dd>一个可选的参数为权限请求的结果的回调函数。此参数已废弃,请使用Promise的语法。</dd>
</dl>

<h3 id="返回值">返回值</h3>

<p>一个 {{jsxref("Promise")}} ,将解析为一个 {{domxref("DOMString")}} ,它是用户对权限请求的选择。这个字符串可以是 <code>granted</code>(被授予), <code>denied</code>(被拒绝) 或者 <code>default</code>(默认)。</p>

<h2 id="实例">实例</h2>

<p>下面这个代码片段将向用户请求权限,然后根据用户的不同选择,输出不同的日志。</p>

<pre class="brush: js">Notification.requestPermission().then(function(result) {
  if (result === 'denied') {
    console.log('Permission wasn\'t granted. Allow a retry.');
    return;
  }
  if (result === 'default') {
    console.log('The permission request was dismissed.');
    return;
  }
  // Do something with the granted permission.
});</pre>

<h2 id="标准">标准</h2>

<table class="standard-table">
 <tbody>
  <tr>
   <th scope="col">Specification</th>
   <th scope="col">Status</th>
   <th scope="col">Comment</th>
  </tr>
  <tr>
   <td>{{SpecName('Web Notifications')}}</td>
   <td>{{Spec2('Web Notifications')}}</td>
   <td>Living standard</td>
  </tr>
 </tbody>
</table>

<h2 id="浏览器兼容性">浏览器兼容性</h2>

{{Compat("api.Notification.requestPermission")}}

<h2 id="参见">参见</h2>

<ul>
 <li><a href="/zh-CN/docs/Web/API/notification/Using_Web_Notifications">使用Web Notifications</a></li>
</ul>