From 33058f2b292b3a581333bdfb21b8f671898c5060 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:40:17 -0500 Subject: initial commit --- files/zh-cn/web/api/client/postmessage/index.html | 134 ++++++++++++++++++++++ 1 file changed, 134 insertions(+) create mode 100644 files/zh-cn/web/api/client/postmessage/index.html (limited to 'files/zh-cn/web/api/client/postmessage') diff --git a/files/zh-cn/web/api/client/postmessage/index.html b/files/zh-cn/web/api/client/postmessage/index.html new file mode 100644 index 0000000000..842029d9db --- /dev/null +++ b/files/zh-cn/web/api/client/postmessage/index.html @@ -0,0 +1,134 @@ +--- +title: Client.postMessage() +slug: Web/API/Client/postMessage +translation_of: Web/API/Client/postMessage +--- +

{{SeeCompatTable}}{{APIRef("Client")}}

+ +

{{domxref("Client")}} 接口的 Client.postMessage() 方法允许一个service worker客户端向一个  {{domxref("ServiceWorker")}}发送一个消息,会触发service worker的message事件,通过监听这个事件,可以获取这个消息。

+ +

语法

+ +
Client.postMessage(message[, transfer]);
+ +

返回

+ +

Void.

+ +

参数

+ +
+
message
+
发送给service worker的消息内容。
+
transfer {{optional_inline}}
+
可转移的对象,例如对端口的引用。
+
+ +

例子

+ +

从 service worker 向 client 发送消息:

+ +
addEventListener('fetch', event => {
+  event.waitUntil(async function() {
+    // Exit early if we don't have access to the client.
+    // Eg, if it's cross-origin.
+    if (!event.clientId) return;
+
+    // Get the client.
+    const client = await clients.get(event.clientId);
+    // Exit early if we don't get the client.
+    // Eg, if it closed.
+    if (!client) return;
+
+    // Send a message to the client.
+    client.postMessage({
+      msg: "Hey I just got a fetch from you!",
+      url: event.request.url
+    });
+
+  }());
+});
+ +

接收message:

+ +
navigator.serviceWorker.addEventListener('message', event => {
+  console.log(event.data.msg, event.data.url);
+}); 
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Service Workers', '#client-postmessage-method', 'postMessage()')}}{{Spec2('Service Workers')}}Initial definition.
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(45.0)}}[1]{{ CompatGeckoDesktop("44.0") }}[2]{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatNo}}{{ CompatGeckoMobile("44.0") }}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatChrome(45.0)}} [1]
+
+ + -- cgit v1.2.3-54-g00ecf