From 06fa9cd9bc783d13d0a403368077d2d0e504f655 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Marcos=20C=C3=A1ceres?=
This example shows a basic share operation. In response to a button
click, this JavaScript code shares the current page's URL.
Usage Examples
+
+ Sharing text and links
+
+
shareButton.addEventListener("click", async () => {
try {
await navigator.share({ title: "Example Page", url: "" });
@@ -99,9 +102,33 @@
display a picker or chooser dialog, allowing the user to select a
target to share this title and the page URL to.
+ This example shows how to share a file. Note that the + {{ShareData/files}} member is an array, allowing for multiple files to + be shared. +
++ shareButton.addEventListener("click", async () => { + const file = new File(data, "some.png", { type: "image/png" }); + try { + await navigator.share({ + title: "Example File", + files: [file] + }); + } catch (err) { + console.error("Share failed:", err.message); + } + }); ++
Calling {{Navigator/canShare()}} method with a {{ShareData}} dictionary - [=validate share data|validates=] the shared data. unlike + [=validate share data|validates=] the shared data. Unlike {{Navigator/share()}}, it can be called without [=transient activation=].
@@ -118,6 +145,49 @@+ Because of how WebIDL dictionaries work, members passed to + {{Navigator/share(())}} that are unknown to the user agent are ignored. + This can be a problem when sharing multiple members, but the user agent + doesn't support sharing one of those members. To be sure that every + member being passed is supported by the user agent, you can pass them + to {{Navigator/canShare()}} individually to check if they are + supported. +
++ const data = { + title: "Example Page", + url: "https://example.com", + text: "This is a text to share", + someFutureThing: "some future thing", + }; + const allSupported = Object.entries(data).every(([key, value]) => { + return navigator.canShare({ [key]: value }); + }); + if (allSupported) { + await navigator.share(data); + } ++
+ Alternatively, you can adjust application's UI to not show UI + components for unsupported members. +
++ const data = { + title: "Example Page", + url: "https://example.com", + text: "This is a text to share", + someFutureThing: "some future thing", + }; + + // Things that are not supported... + const unsupported = Object.entries(data).filter(([key, value]) => { + return !navigator.canShare({ [key]: value }); + }); +