Below code works well on devices where web share API is supported and shows the native share dialog but throughs "Uncaught (in promise) DOMException: Share canceled" error where web share API is not supported and do not goes to the URL defined in href of the anchor tag.
<a href="https://example.com?utm_source=btn_share" class="btn-share" target="_blank">
Share on Facebook
</a>
<script type="text/javascript">
$(".btn-share").click(function(e){
// Web Share API
if (navigator.share){
e.preventDefault();
navigator.share({
title: 'This is example website',
url: 'https://example.com'
});
}
});
</script>
Remove the error so that it should go to the URL defined in href of the anchor tag if web share API is not supported on the device.
2
Answers
Since
navigator.share
is a promise, I would just catch the error, set a prop on the link letting you know it errors, and then simulate another click.https://jsfiddle.net/n672g4kr/
(Stackoverflow won’t open a new window from a fiddle apperently)
You need to catch the error as
navigator.share()
is a Promise,Promise returns "AbortError" If the user chose to cancel the share operation(mostly on mobile devices) or if there are no share targets available (it occurs mostly on desktop devices). So differentiating the "AbortError" on mobile devices and on desktop computer needs some extra mechanism.
Reference: https://www.w3.org/TR/web-share/
The best solution to your problem at the moment is:
https://jsfiddle.net/g19but5o/2/