aboutsummaryrefslogtreecommitdiff
path: root/files/ru/web/api/serviceworkercontainer
diff options
context:
space:
mode:
authorPeter Bengtsson <mail@peterbe.com>2020-12-08 14:42:52 -0500
committerPeter Bengtsson <mail@peterbe.com>2020-12-08 14:42:52 -0500
commit074785cea106179cb3305637055ab0a009ca74f2 (patch)
treee6ae371cccd642aa2b67f39752a2cdf1fd4eb040 /files/ru/web/api/serviceworkercontainer
parentda78a9e329e272dedb2400b79a3bdeebff387d47 (diff)
downloadtranslated-content-074785cea106179cb3305637055ab0a009ca74f2.tar.gz
translated-content-074785cea106179cb3305637055ab0a009ca74f2.tar.bz2
translated-content-074785cea106179cb3305637055ab0a009ca74f2.zip
initial commit
Diffstat (limited to 'files/ru/web/api/serviceworkercontainer')
-rw-r--r--files/ru/web/api/serviceworkercontainer/controller/index.html55
-rw-r--r--files/ru/web/api/serviceworkercontainer/index.html165
-rw-r--r--files/ru/web/api/serviceworkercontainer/register/index.html140
3 files changed, 360 insertions, 0 deletions
diff --git a/files/ru/web/api/serviceworkercontainer/controller/index.html b/files/ru/web/api/serviceworkercontainer/controller/index.html
new file mode 100644
index 0000000000..066edb858b
--- /dev/null
+++ b/files/ru/web/api/serviceworkercontainer/controller/index.html
@@ -0,0 +1,55 @@
+---
+title: ServiceWorkerContainer.controller
+slug: Web/API/ServiceWorkerContainer/controller
+translation_of: Web/API/ServiceWorkerContainer/controller
+---
+<div>{{APIRef("Service Workers API")}}</div>
+
+<p><span class="seoSummary">Свойство <strong><code>controller</code></strong> интерфейса {{domxref("ServiceWorkerContainer")}} возвращает объект {{domxref("ServiceWorker")}}, в случае, если service worker активирован. Данное свойство возвращает <code>null</code>, если страница была обновлена с помощью <em>Shift</em> + refresh или на ней отсутствует активный service worker.</span></p>
+
+<h2 id="Синтаксис">Синтаксис</h2>
+
+<pre class="syntaxbox">var myController = navigator.serviceWorker.controller;
+</pre>
+
+<h3 id="Значение">Значение</h3>
+
+<p>Объект {{domxref("ServiceWorker")}}.</p>
+
+<h2 id="Пример">Пример</h2>
+
+<pre class="brush: js">if ('serviceWorker' in navigator) {
+ // Проверяем, находится ли данная страница под управлением service worker.
+ if (navigator.serviceWorker.controller) {
+ console.log(`Эта страница сейчас контролируется ${navigator.serviceWorker.controller}`);
+ } else {
+  console.log('Эта страница не контролируется service worker.');
+  }
+} else {
+ console.log('Данный браузер не поддерживает Service Worker API.');
+}</pre>
+
+<h2 id="Спецификации">Спецификации</h2>
+
+<table class="standard-table">
+ <tbody>
+ <tr>
+ <th scope="col">Спецификация</th>
+ <th scope="col">Статус</th>
+ <th scope="col">Комментарии</th>
+ </tr>
+ <tr>
+ <td>{{SpecName('Service Workers', '#navigator-service-worker-controller', 'ServiceWorkerRegistration.controller')}}</td>
+ <td>{{Spec2('Service Workers')}}</td>
+ <td>Изначальное определение.</td>
+ </tr>
+ </tbody>
+</table>
+
+<h2 id="Совместимость">Совместимость</h2>
+
+<div>
+
+
+<p>{{Compat("api.ServiceWorkerContainer.controller")}}</p>
+</div>
diff --git a/files/ru/web/api/serviceworkercontainer/index.html b/files/ru/web/api/serviceworkercontainer/index.html
new file mode 100644
index 0000000000..a8bf9f324e
--- /dev/null
+++ b/files/ru/web/api/serviceworkercontainer/index.html
@@ -0,0 +1,165 @@
+---
+title: ServiceWorkerContainer
+slug: Web/API/ServiceWorkerContainer
+tags:
+ - API
+ - Draft
+ - Interface
+ - NeedsTranslation
+ - Offline
+ - Reference
+ - Service Workers
+ - ServiceWorkerContainer
+ - TopicStub
+ - Workers
+translation_of: Web/API/ServiceWorkerContainer
+---
+<p>{{SeeCompatTable}}{{APIRef("Service Workers API")}}</p>
+
+<p><a href="/en-US/docs/Web/API/ServiceWorker_API">ServiceWorker API</a> предоставляет интерфейс <code>ServiceWorkerContainer</code>, являющийся объектом (объект предствляет собой сервис воркер, как единое целое в сетевой экосистеме) влючающим следующие средства:<br>
+ Регистрация;<br>
+ Отмена регистрации;<br>
+ Обновление сервис воркеров;<br>
+ Доступ к состоянию сервис воркеров;<br>
+ Доступ к регистрации сервис воркеров.</p>
+
+<p>Most importantly, it exposes the {{domxref("ServiceWorkerContainer.register", "ServiceWorkerContainer.register(scriptURL, scope[, base])")}} method used to register service workers, and the {{domxref("ServiceWorkerContainer.controller")}} property used to determine whether or not the current page is actively controlled.</p>
+
+<h2 id="Properties">Properties</h2>
+
+<dl>
+ <dt>{{domxref("ServiceWorkerContainer.controller")}} {{readonlyinline}}</dt>
+ <dd>Returns a {{domxref("ServiceWorker")}} object if its state is <code>activated</code> (the same object returned by {{domxref("ServiceWorkerRegistration.active")}}). This property returns <code style="font-style: normal;">null</code> if the request is a force refresh (<em>Shift</em> + refresh) or if there is no active worker.</dd>
+</dl>
+
+<dl>
+ <dt>{{domxref("ServiceWorkerContainer.ready")}} {{readonlyinline}}</dt>
+ <dd>Defines whether a service worker is ready to control a page or not. It returns a {{jsxref("Promise")}} that will never reject, which resolves to a {{domxref("ServiceWorkerRegistration")}} with an {{domxref("ServiceWorkerRegistration.active")}} worker.</dd>
+</dl>
+
+<h3 id="Event_handlers">Event handlers</h3>
+
+<dl>
+ <dt>{{domxref("ServiceWorkerContainer.oncontrollerchange")}}</dt>
+ <dd>An event handler fired whenever a {{Event("controllerchange")}} event occurs — when the document's associated {{domxref("ServiceWorkerRegistration")}} acquires a new {{domxref("ServiceWorkerRegistration.active")}} worker.</dd>
+ <dt>{{domxref("ServiceWorkerContainer.onerror")}}</dt>
+ <dd>An event handler fired whenever an {{Event("error")}} event occurs in the associated service workers.</dd>
+ <dt>{{domxref("ServiceWorkerContainer.onmessage")}}</dt>
+ <dd>An event handler fired whenever a {{Event("message")}} event occurs — when incoming messages are received to the {{domxref("ServiceWorkerContainer")}} object (e.g. via a {{domxref("MessagePort.postMessage()")}} call.)</dd>
+</dl>
+
+<h2 id="Methods">Methods</h2>
+
+<dl>
+ <dt>{{domxref("ServiceWorkerContainer.register", "ServiceWorkerContainer.register()")}} </dt>
+ <dd>Creates or updates a {{domxref("ServiceWorkerRegistration")}} for the given <code>scriptURL</code>.</dd>
+ <dt>{{domxref("ServiceWorkerContainer.getRegistration()")}}</dt>
+ <dd>Gets a {{domxref("ServiceWorkerRegistration")}} object whose scope URL matches the provided document URL.  If the method can't return a {{domxref("ServiceWorkerRegistration")}}, it returns a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" style="text-decoration: underline;" title="The Promise object is used for deferred and asynchronous computations. A Promise is in one of the three states:"><code>Promise</code></a>. </dd>
+ <dt>{{domxref("ServiceWorkerContainer.getRegistrations()")}}</dt>
+ <dd>Returns all {{domxref("ServiceWorkerRegistration")}}s associated with a <code>ServiceWorkerContainer</code> in an array.  If the method can't return {{domxref("ServiceWorkerRegistration")}}s, it returns a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" style="text-decoration: underline;" title="The Promise object is used for deferred and asynchronous computations. A Promise is in one of the three states:"><code>Promise</code></a>. </dd>
+</dl>
+
+<h2 id="Examples">Examples</h2>
+
+<p>This code snippet is from the <a href="https://github.com/GoogleChrome/samples/blob/gh-pages/service-worker/fallback-response/index.html#L126">service worker fallback-response sample</a> (see <a href="http://googlechrome.github.io/samples/service-worker/fallback-response/">fallback-response live</a>). The code checks to see if the browser supports service workers. Then the code registers the service worker and determines if the page is actively controlled by the service worker. If it isn't, it prompts the user to reload the page so the service worker can take control. The code also reports any registration failures.</p>
+
+<pre class="brush: js">if ('serviceWorker' in navigator) {
+ navigator.serviceWorker.register('service-worker.js', {scope: './'}).then(function() {
+ if (navigator.serviceWorker.controller) {
+ document.querySelector('#status').textContent = 'The service worker is currently handling network operations.';
+ showRequestButtons();
+ } else {
+ document.querySelector('#status').textContent = 'Please reload this page to allow the service worker to handle network operations.';
+ }
+ }).catch(function(error) {
+ document.querySelector('#status').textContent = error;
+ });
+} else {
+ var aElement = document.createElement('a');
+ aElement.href = 'http://www.chromium.org/blink/serviceworker/service-worker-faq';
+ aElement.textContent = 'unavailable';
+ document.querySelector('#status').appendChild(aElement);
+}</pre>
+
+<h2 id="Specifications">Specifications</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('Service Workers', '#service-worker-container', 'ServiceWorkerContainer')}}</td>
+ <td>{{Spec2('Service Workers')}}</td>
+ <td>Initial definition.</td>
+ </tr>
+ </tbody>
+</table>
+
+<h2 id="Browser_compatibility">Browser compatibility</h2>
+
+<div>{{CompatibilityTable}}</div>
+
+<div id="compat-desktop">
+<table class="compat-table">
+ <tbody>
+ <tr>
+ <th>Feature</th>
+ <th>Chrome</th>
+ <th>Firefox (Gecko)</th>
+ <th>Internet Explorer</th>
+ <th>Opera</th>
+ <th>Safari (WebKit)</th>
+ </tr>
+ <tr>
+ <td>Basic support</td>
+ <td>{{CompatChrome(40.0)}}</td>
+ <td>{{ CompatGeckoDesktop("44.0") }}<sup>[1]</sup></td>
+ <td>{{CompatNo}}</td>
+ <td>24</td>
+ <td>{{CompatNo}}</td>
+ </tr>
+ </tbody>
+</table>
+</div>
+
+<div id="compat-mobile">
+<table class="compat-table">
+ <tbody>
+ <tr>
+ <th>Feature</th>
+ <th>Android</th>
+ <th>Firefox Mobile (Gecko)</th>
+ <th>Firefox OS</th>
+ <th>IE Mobile</th>
+ <th>Opera Mobile</th>
+ <th>Safari Mobile</th>
+ <th>Chrome for Android</th>
+ </tr>
+ <tr>
+ <td>Basic support</td>
+ <td>{{CompatUnknown}}</td>
+ <td>{{ CompatGeckoMobile("44.0") }}</td>
+ <td>{{ CompatVersionUnknown }}</td>
+ <td>{{CompatNo}}</td>
+ <td>{{CompatUnknown}}</td>
+ <td>{{CompatNo}}</td>
+ <td>{{CompatUnknown}}</td>
+ </tr>
+ </tbody>
+</table>
+</div>
+
+<p>[1] Service workers (and <a href="/en-US/docs/Web/API/Push_API">Push</a>) have been disabled in the <a href="https://www.mozilla.org/en-US/firefox/organizations/">Firefox 45 Extended Support Release</a> (ESR.)</p>
+
+<h2 id="See_also">See also</h2>
+
+<ul>
+ <li><a href="https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker_API/Using_Service_Workers">Using Service Workers</a></li>
+ <li><a class="external external-icon" href="https://github.com/mdn/sw-test">Service workers basic code example</a></li>
+ <li><a class="external external-icon" href="https://jakearchibald.github.io/isserviceworkerready/">Is ServiceWorker ready?</a></li>
+ <li>{{jsxref("Promise")}}</li>
+ <li><a href="https://developer.mozilla.org/en-US/docs/Web/Guide/Performance/Using_web_workers">Using web workers</a></li>
+</ul>
diff --git a/files/ru/web/api/serviceworkercontainer/register/index.html b/files/ru/web/api/serviceworkercontainer/register/index.html
new file mode 100644
index 0000000000..a885e08102
--- /dev/null
+++ b/files/ru/web/api/serviceworkercontainer/register/index.html
@@ -0,0 +1,140 @@
+---
+title: ServiceWorkerContainer.register()
+slug: Web/API/ServiceWorkerContainer/register
+translation_of: Web/API/ServiceWorkerContainer/register
+---
+<p>{{SeeCompatTable}}{{APIRef("Service Workers API")}}</p>
+
+<p><strong><code>register()</code></strong> метод {{domxref("ServiceWorkerContainer")}} интерфейса который создает и обновляет <a href="https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerRegistration" title="The ServiceWorkerRegistion interface of the ServiceWorker API represents the service worker registration. You register a service worker to control one or more pages that share the same origin."><code>ServiceWorkerRegistration</code></a>  для указанного <code>URL js скрипта</code>.</p>
+
+<p>Если удачно, service worker registration связывается по указанному URL js скрипта , который соответственно используется для проверки совпадения при навигации по URL. Если метод не возвращает <code>ServiceWorkerRegistration</code>, он возвращает <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" title="The Promise object is used for deferred and asynchronous computations. A Promise is in one of the three states:"><code>Promise</code></a>. Есть возможность вызвать этот метод без проверки на условие, т.е. нет необходимости сначала проверять существует ли активная регистрация в данный момент или нет.</p>
+
+<h2 id="Синтаксис">Синтаксис</h2>
+
+<pre class="brush: js notranslate">ServiceWorkerContainer.register(scriptURL, options)
+ .then(function(ServiceWorkerRegistration) { ... });</pre>
+
+<h3 id="Параметры">Параметры</h3>
+
+<dl>
+ <dt><code>scriptURL</code></dt>
+ <dd>URL скрипта service worker - а.</dd>
+ <dt><code>options</code> <code>{{optional_inline}}</code></dt>
+ <dd>Опции — это обьект  необходимый для регистрации service worker-a. В данный момент доступные опции:
+ <ul>
+ <li><code>scope</code>: {{domxref("USVString")}} представляет собой URL, который определяет scope service worker-a; Какой диапазон URL может контролировать service worker. Это обычно относительный URL. Значение по умолчанию — это URL,  который соответствует корню, т.е. './', используя дирректорию расположения js скрипта service worker-а как основу.</li>
+ </ul>
+ </dd>
+</dl>
+
+<h3 id="Возвращает">Возвращает</h3>
+
+<p>{{domxref("Promise")}} который резолвится в {{domxref("ServiceWorkerRegistration")}} обьект.</p>
+
+<h2 id="Пример_использования">Пример использования</h2>
+
+<p>Примеры кода, приведенные ниже, должны рассматриваться вместе для лучшего понимания того, как применяется scope service worker-ов к конкретной странице.</p>
+
+<p>Следующий пример использует дефолтный scope (не указывая его прямо). Service worker в этом случае будет контролировать <code>example.com/index.html</code> и страницы, расположенные "глубже", например <code>example.com/product/description.html</code>.</p>
+
+<pre class="brush: js notranslate">if ('serviceWorker' in navigator) {
+ // Регистрация service worker-а, расположенного в корне сайта
+  // за счет использования дефолтного scope (не указывая его)
+  navigator.serviceWorker.register('/sw.js').then(function(registration) {
+    console.log('Service worker зарегистрирован:', registration);
+  }).catch(function(error) {
+    console.log('Ошибка при регистрации service worker-а:', error);
+  });
+} else {
+  // Текущий браузер не поддерживает service worker-ы.
+  console.log('Текущий браузер не поддерживает service worker-ы');
+}</pre>
+
+<p>Следующий пример, если он размещен на странице корня сайта, будет применен ровно к тем же страницам, что и пример выше. Помните, scope, если он указан, использует path страницы в качестве своей базы. Это значит, что, если следующий пример будет использоваться на странице <code>example.com/product/description.html</code>, то scope <code>./</code> будет означать, что service worker работает только со страницами внутри <code>example.com/product</code>. Если необходимо зарегистрировать service worker на <code>example.com/product/description.html</code>, и вы хотите, чтобы он обслуживал и корень, <code>example.com</code>, то scope лучше не указывать совсем, как в примере выше.</p>
+
+<pre class="brush: js notranslate">if ('serviceWorker' in navigator) {
+  // Регистрация service worker-а, расположенного в корне сайта
+  // с указанием более строгого scope
+ navigator.serviceWorker.register('/sw.js', {scope: './'}).then(function(registration) {
+ console.log('Service worker зарегистрирован:', registration);
+ }).catch(function(error) {
+ console.log('Ошибка при регистрации service worker-а:', error);
+ });
+} else {
+ console.log('Текущий браузер не поддерживает service worker-ы.');
+}</pre>
+
+
+
+<h2 id="Спецификация">Спецификация</h2>
+
+<table class="standard-table">
+ <tbody>
+ <tr>
+ <th scope="col">Спецификация</th>
+ <th scope="col">Статус</th>
+ <th scope="col">Комментарии</th>
+ </tr>
+ <tr>
+ <td>{{SpecName('Service Workers', '#service-worker-container', 'ServiceWorkerContainer')}}</td>
+ <td>{{Spec2('Service Workers')}}</td>
+ <td>Первичное определение.</td>
+ </tr>
+ </tbody>
+</table>
+
+<h2 id="Браузерная_совместимость">Браузерная совместимость</h2>
+
+<div>{{CompatibilityTable}}</div>
+
+<div id="compat-desktop">
+<table class="compat-table">
+ <tbody>
+ <tr>
+ <th>Feature</th>
+ <th>Chrome</th>
+ <th>Firefox (Gecko)</th>
+ <th>Internet Explorer</th>
+ <th>Opera</th>
+ <th>Safari (WebKit)</th>
+ </tr>
+ <tr>
+ <td>Начальная поддержка</td>
+ <td>{{CompatChrome(40.0)}}</td>
+ <td>{{ CompatGeckoDesktop("44.0") }}<sup>[1]</sup></td>
+ <td>{{CompatNo}}</td>
+ <td>24</td>
+ <td>{{CompatNo}}</td>
+ </tr>
+ </tbody>
+</table>
+</div>
+
+<div id="compat-mobile">
+<table class="compat-table">
+ <tbody>
+ <tr>
+ <th>Feature</th>
+ <th>Android</th>
+ <th>Firefox Mobile (Gecko)</th>
+ <th>Firefox OS</th>
+ <th>IE Mobile</th>
+ <th>Opera Mobile</th>
+ <th>Safari Mobile</th>
+ <th>Chrome for Android</th>
+ </tr>
+ <tr>
+ <td>Начальная поддержка</td>
+ <td>{{CompatUnknown}}</td>
+ <td>{{ CompatGeckoMobile("44.0") }}</td>
+ <td>{{ CompatVersionUnknown }}</td>
+ <td>{{CompatNo}}</td>
+ <td>{{CompatUnknown}}</td>
+ <td>{{CompatNo}}</td>
+ <td>{{CompatChrome(40.0)}}</td>
+ </tr>
+ </tbody>
+</table>
+</div>
+
+<p>[1] Использование Service worker ( и <a href="/en-US/docs/Web/API/Push_API">Push</a>) приостановлено в <a href="https://www.mozilla.org/en-US/firefox/organizations/">Firefox 45 Extended Support Release</a> (ESR.)</p>