--- 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
options
{{optional_inline}}
scope
: 一个 {{domxref("USVString")}},表示定义service worker注册范围的URL ;service worker可以控制的URL范围。通常是相对URL。默认值是基于当前的location,并以此来解析传入的路径.返回一个 {{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. |
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.)