Simple share button. But not that simple.

Recently I had inqusite encounter with a task to try experementaly use Web Share API. This is a cool feature that can invoke your device internal sharing mechanizms. In nutshell, it would open Android or iOS native share menu. In fact it works with a few more devices/browsers, you can check it out here.

Here is a simple example that could help you use it.
Note that when you want to invoke this API you should invoke it using some user events (user should invoke it manuall i.e. press a button). Otherwise it wouldn’t work and display an error that the request is not permitted/blocked by user.
You can use these user activation events:
* change
* click
* contextmenu
* dblclick
* mouseup
* pointerup
* reset
* submit
* touchend

So, just put a button where you need it:

<button class="test-share">Share</button>

And then on example with jQuery, you could do it this way:

$('.test-share').off().on("click", async function() {
    var obj = {
        "title": "test",
        "url": window.location.href,
        "text": "Text you want to display along with shared link"
    }
    try { 
        await window.navigator.share(obj);
    } catch(err) {
        console.log(err);
    }
});

Actually, the part with window.navigator.share(obj) would be the same no matter what you use (TS, Dart, pure JS) as you basically need to work with native JS here.

After you implement it, pressing on the “share” button will open the native share menu of your device.

Please, do check whether this API is available for the device it would be used on. E.g. hide this button if there is no share function available: if (typeof window.navigator.share !== "function") { // hide button }.

Cheers!

If you have found a spelling error, please, notify us by selecting that text and pressing Ctrl+Enter.

Leave a Reply

Your email address will not be published. Required fields are marked *