Skip to content

Instantly share code, notes, and snippets.

@adactio
Last active April 13, 2024 19:22
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adactio/092b11a74eded2701335ba27f94d2484 to your computer and use it in GitHub Desktop.
Save adactio/092b11a74eded2701335ba27f94d2484 to your computer and use it in GitHub Desktop.
A polyfill for `button type="share"`
// Licensed under a CC0 1.0 Universal (CC0 1.0) Public Domain Dedication
// http://creativecommons.org/publicdomain/zero/1.0/
/* Use <button type="share"> in your HTML.
Include this JavaScript in a <script> element on the same page or in an external script.
The script checks for three ways of sharing:
1. Native support for <button type="share">.
2. Support for the JavaScript Web Share API.
3. A mailto: link.
This will share the current URL and page title.
*/
(function (win, doc) {
const testButton = doc.createElement('button');
testButton.setAttribute('type','share');
if (testButton.type != 'share') {
win.addEventListener('click', function(ev) {
ev = ev || win.event;
let target = ev.target;
let button = target.closest('button[type="share"]');
if (button) {
const title = doc.querySelector('title').innerText;
const url = win.location.href;
if (navigator.share) {
navigator.share({ title: title, url: url });
} else {
win.location.href='mailto:?subject='+title+'&body='+url;
}
}
});
}
}(this, this.document));
@adactio
Copy link
Author

adactio commented Sep 30, 2020

@adactio
Copy link
Author

adactio commented Sep 30, 2020

@jonathantneal
Copy link

In Safari 14.0, my experience with the navigator.share API and the default Mail app is that the title property is ignored, the text property is added to the body of the message, and the url is appended below it on a new line.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment