Skip to content

Instantly share code, notes, and snippets.

@adactio

adactio/sharebutton.js

Last active Nov 11, 2020
Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

@adactio adactio commented Sep 30, 2020

@adactio

This comment has been minimized.

Copy link
Owner Author

@adactio adactio commented Sep 30, 2020

@jonathantneal

This comment has been minimized.

Copy link

@jonathantneal jonathantneal commented Nov 11, 2020

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