From 56af71917c09bd426f73043a174a9cdb5941d4d7 Mon Sep 17 00:00:00 2001 From: Michael Rienstra Date: Sat, 16 Sep 2023 18:52:36 -0700 Subject: [PATCH] Improve navigator.share example Better error handling, was failing silently when not supported. New version is similar to code example at https://developer.mozilla.org/en-US/docs/Web/API/Navigator/canShare#examples --- web-share/index.html | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/web-share/index.html b/web-share/index.html index 22d0a538..836d9423 100644 --- a/web-share/index.html +++ b/web-share/index.html @@ -22,18 +22,26 @@

Sharing MDN

title: 'MDN', text: 'Learn web development on MDN!', url: 'https://developer.mozilla.org', - } + }; const btn = document.querySelector('button'); const resultPara = document.querySelector('.result'); btn.addEventListener('click', () => { + if (!navigator.canShare) { + resultPara.textContent = 'Web Share API not available'; + return; + } + if (!navigator.canShare(shareData)) { + resultPara.textContent = 'Share data unsupported, disallowed, or invalid'; + return; + } navigator.share(shareData) .then(() => - resultPara.textContent = 'MDN shared successfully' + resultPara.textContent = 'MDN shared successfully'; ) .catch((e) => - resultPara.textContent = 'Error: ' + e + resultPara.textContent = 'Error: ' + e; ) });