aboutsummaryrefslogtreecommitdiff
path: root/files/ru/web/api/pushmanager/subscribe/index.html
blob: a970f48612fbc952a79974d4b6cdb6e9f12a1116 (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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
---
title: PushManager.subscribe()
slug: Web/API/PushManager/subscribe
translation_of: Web/API/PushManager/subscribe
---
<p>{{SeeCompatTable}}{{ApiRef("Push API")}}</p>

<p><code style=""><font face="Arial, x-locale-body, sans-serif"><span style="background-color: #ffffff;">Метод </span></font><strong>subscribe()</strong></code> интерфейса {{domxref("PushManager")}} позволяет осуществлять подписку на push-уведомления.</p>

<p>Возвращает {{jsxref("Promise")}}, который разрешается в объект {{domxref("PushSubscription")}}, содержащий детали push-подписки. Новая push-подписка создаётся в случае, если сервис-воркер не имеет существующей подписки.</p>

<h2 id="Синтаксис">Синтаксис</h2>

<pre class="syntaxbox">​PushManager.subscribe(options).then(function(pushSubscription) { ... } );</pre>

<h3 id="Свойства">Свойства</h3>

<dl>
 <dt><code>options {{optional_inline}}</code></dt>
 <dd>Объект, содержащий необязательные параметры конфигурации. Может иметь следующие свойства:
 <ul>
  <li><code>userVisibleOnly</code>: Булевое значение, указывающее на то, будет ли возвращаемая подписка использоваться для сообщений, чей эффект может быть видим для пользователя.</li>
  <li><code>applicationServerKey</code>: открытый ключ ECDSA P-256, закодированный в Base64 {{domxref ('DOMString')}} или {{domxref ('ArrayBuffer')}}}, содержащий , который push-сервер будет использовать для аутентификации сервера приложений. Если указано, все сообщения с сервера вашего приложения должны использовать схему аутентификации VAPID и включать JWT, подписанный соответствующим закрытым ключом. Этот ключ <strong><em>НЕ </em></strong>тот же ключ ECDH, который вы используете для шифрования данных. Для получения дополнительной информации см. «<a href="https://blog.mozilla.org/services/2016/04/04/using-vapid-with-webpush/">Using VAPID with WebPush</a>».</li>
 </ul>

 <div class="blockIndicator note">
 <p><em><strong>Примечание: </strong>Свойство, требуемое некоторыми браузерами, например Chrome и Edge.</em></p>
 </div>
 </dd>
</dl>

<h3 id="Возвращает">Возвращает</h3>

<p>{{jsxref("Promise")}} который разрешается в объект {{domxref("PushSubscription")}}.</p>

<h2 id="Пример">Пример</h2>

<pre class="brush: js">this.onpush = function(event) {
  console.log(event.data);
  <code>// Отсюда можно записывать данные в IndexedDB, отправлять их в любое
  // открытое окно, отображать уведомление и т. д.</code>
}

navigator.serviceWorker.register('serviceworker.js').then(
  function(serviceWorkerRegistration) {
    serviceWorkerRegistration.pushManager.subscribe().then(
      function(pushSubscription) {
        console.log(pushSubscription.subscriptionId);
        console.log(pushSubscription.endpoint);
        <code>// Детали push-подписки, требуемые сервером приложения,
        // теперь доступны, и могут быть отправлены, к примеру,
        // при помощи XMLHttpRequest.</code>
      }, function(error) {
        <code>// При разработке это часто помогает отлавливать ошибки в консоли.
        // В продакшен-среде это также может быть полезно для отправки отчёта
        // об ошибках на сервер приложения.</code>
        console.log(error);
      }
    );
  });</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('Push API', '#widl-PushManager-subscribe-Promise-PushSubscription--PushSubscriptionOptions-options', 'subscribe()')}}</td>
   <td>{{Spec2('Push API')}}</td>
   <td>Initial definition.</td>
  </tr>
 </tbody>
</table>

<h2 id="Совместимость_с_браузерами">Совместимость с браузерами</h2>

<div>{{CompatibilityTable}}</div>

<div id="compat-desktop">
<table class="compat-table">
 <tbody>
  <tr>
   <th style="line-height: 16px;">Feature</th>
   <th style="line-height: 16px;">Chrome</th>
   <th style="line-height: 16px;">Firefox (Gecko)</th>
   <th style="line-height: 16px;">Internet Explorer</th>
   <th style="line-height: 16px;">Opera</th>
   <th style="line-height: 16px;">Safari (WebKit)</th>
  </tr>
  <tr>
   <td>Basic support</td>
   <td>{{CompatChrome(42.0)}}</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatUnknown}}</td>
  </tr>
 </tbody>
</table>
</div>

<div id="compat-mobile">
<table class="compat-table">
 <tbody>
  <tr>
   <th style="line-height: 16px;">Feature</th>
   <th style="line-height: 16px;">Android</th>
   <th style="line-height: 16px;">Android Webview</th>
   <th style="line-height: 16px;">Firefox Mobile (Gecko)</th>
   <th style="line-height: 16px;">Firefox OS</th>
   <th style="line-height: 16px;">IE Mobile</th>
   <th style="line-height: 16px;">Opera Mobile</th>
   <th style="line-height: 16px;">Safari Mobile</th>
   <th style="line-height: 16px;">Chrome for Android</th>
  </tr>
  <tr>
   <td>Basic support</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatChrome(42.0)}}</td>
  </tr>
 </tbody>
</table>
</div>

<h2 id="Смотрите_также">Смотрите также</h2>

<ul>
 <li><a href="/en-US/docs/Web/API/Push_API/Using_the_Push_API">Using the Push API</a></li>
 <li><a href="http://updates.html5rocks.com/2015/03/push-notificatons-on-the-open-web">Push Notifications on the Open Web</a>, Matt Gaunt</li>
</ul>

<p> </p>

<p> </p>