Skip to content

Instantly share code, notes, and snippets.

@adactio

adactio/sharebutton.js

Last active Sep 22, 2020
Embed
What would you like to do?
A polyfill for `button type="share"`
/* 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));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.