Sharing is caring
Greg, The JavaScript Whisperer
Posted on August 10, 2020
Wouldn't it be grand to click a button and have your mobile's native share dialog come up?
This used to take funky third party js widgets, or registering for all the various site api's individual; I remember it could take a week to get it right with SEO back in the golden days.
Well friends fear no more check out the webshare api
Now hypothetically say you have a fullscreened progressive web app, looks slick don't it? The problem though is the missing url bar.
Example:
Here's your solution in the form of a method. One caveat is this must be called on a user action like click.
share() {
if (navigator.share) {
navigator
.share({
title: 'title',
text: 'description',
url: `url`
})
.catch(err => {
console.log(`Couldn't share because of`, err.message);
});
} else {
console.log("web share not supported");
}
}
<a class="show-mobile" href="#" @click.prevent="share">🔗 share</a>
Oh one more thing, this is only supported on mobile devices. I find this solution better than the user agent sniffing dark arts.
.show-mobile {
display: none;
}
@media (pointer: coarse) {
.show-mobile {
display: inline-block;
}
}
Why not fire up your cellular device and give it a try with this article, how meta would that be?
Posted on August 10, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.