From 878a5da63c31a6c766d6ce02c36df0df9ff0f8e8 Mon Sep 17 00:00:00 2001 From: Michael Rienstra Date: Wed, 17 Jul 2024 15:53:40 -0700 Subject: [PATCH] Improve navigator.share example (#227) 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 Co-authored-by: Brian Thomas Smith --- 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; ) });