Share button for mobile website to invoke iOS/Android system share dialogs
Use the Web Share API to share your URL on iOS or Android via Javascript.
It is supported by
- Chrome since Version 61 (2016) and
- iOS 12.2 is told to add support for it soon (2019).
$('#answer-example-share-button').on('click', () => {
if (navigator.share) {
navigator.share({
title: 'Web Share API Draft',
text: 'Take a look at this spec!',
url: 'https://wicg.github.io/web-share/#share-method',
})
.then(() => console.log('Successful share'))
.catch((error) => console.log('Error sharing', error));
} else {
console.log('Share not supported on this browser, do it the old way.');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id='answer-example-share-button'>Share!</button>
Citing Google Developers:
- you must be served over HTTPS
- you can only invoke the API in response to a user action, such as a click (e.g., you can't call navigator.share as part of the page load)
- you can also share any URL, not just URLs under your website's current scope: and you may also share text without a URL
- you should feature-detect it in case it's not available on your users' platform (e.g., via navigator.share !== undefined)