--- title: ServiceWorkerContainer.register() slug: Web/API/ServiceWorkerContainer/register tags: - ServiceWorkerContainer.register() translation_of: Web/API/ServiceWorkerContainer/register ---

{{SeeCompatTable}}{{APIRef("Service Workers API")}}

{{domxref("ServiceWorkerContainer")}} 接口的 register() 方法创建或更新一个给定scriptURL的ServiceWorkerRegistration 

如果成功,一个服务工作者注册将提供的脚本URL与一个范围进行关联,后者用于导航匹配。如果该方法无法返回一个 ServiceWorkerRegistration,则返回一个 Promise

您可以从受控页无条件调用此方法, 即, 您不需要首先检查是否有一个有效的注册。

语法

ServiceWorkerContainer.register(scriptURL, options)
    .then(
        function(ServiceWorkerRegistration) {
            // do something
        }
);

参数

scriptURL
service worker脚本的URL.
options {{optional_inline}}
注册时提供选项的配置对象。 目前可用的选项包括:

返回

返回一个 {{domxref("Promise")}} 对象, 值是 {{domxref("ServiceWorkerRegistration")}} .

示例

if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('service-worker.js', {scope: './'})
  .then(function(registration) {
    document.querySelector('#status').textContent = 'succeeded';
  }).catch(function(error) {
    document.querySelector('#status').textContent = error;
  });
} else {
  // The current browser doesn't support service workers.
  let aElement = document.createElement('a');
  aElement.href = `
     http://www.chromium.org/blink/serviceworker/service-worker-faq
  `;
  aElement.textContent = 'unavailable';
  document.querySelector('#status').appendChild(aElement);
}

规范

Specification Status Comment
{{SpecName('Service Workers', '#service-worker-container', 'ServiceWorkerContainer')}} {{Spec2('Service Workers')}} Initial definition.

浏览器兼容性

{{CompatibilityTable}}
Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
Basic support {{CompatChrome(40.0)}} {{ CompatGeckoDesktop("44.0") }}[1] {{CompatNo}} 24 {{CompatNo}}
Feature Android Firefox Mobile (Gecko) Firefox OS IE Mobile Opera Mobile Safari Mobile Chrome for Android
Basic support {{CompatUnknown}} {{ CompatGeckoMobile("44.0") }} {{ CompatVersionUnknown }} {{CompatNo}} {{CompatUnknown}} {{CompatNo}} {{CompatChrome(40.0)}}

[1] Service workers (and Push) have been disabled in the Firefox 45 Extended Support Release (ESR.)