Simple sharing on the web with navigator.share

Paul Kinlan

Many of you know that I am passionate about inter-app communications, specifically the action of sharing. One of the things that I have encouraged anyone who wants to do the next version of Web Intents to do is focus on a very small and specific use case.

Well Good News Everybody. Matt Giuca on the Chrome team has been working on a simple API (Web Share) that has the potential to connect websites with native apps and also and it is in Chrome Dev Channel on Android to test. The great thing is that Matt and team have also been working on making it possible for your own web site or service to be registered as a native share receiver thus enabling web->app sharing, app->web sharing and web->web sharing.

It’s all still early stages, but I think it is worth testing out and giving us as much feedback as possible whilst this is getting developed. You can get all the relevant information at ChromeStatus, but to save you a click here are the important links:

I am incredibly excited by this API. It opens an entirely new part of the ecosystem up to web developers and if the Sharing API works well then the model can be extended to other app to app interactions.

How to get this working.

  1. Get Chrome Dev Channel on Android.
  2. Toggle chrome://flags/#enable-experimental-web-platform-features
  3. Go to any page on my blog and click the share button at the end of each article.
  4. Share.
 navigator.share({title: document.title, text: window.location.href, url: window.location.href})
          .then(() => console.log('Successful share'),
           error => console.log('Error sharing:', error));

Here is how I have integrated it into my blog.

  1. Check to see if the API is available, if not fallback to my existing solution
  2. Wait for the content to be available and then find the sharing element
  3. Intercept and consume the click
  4. navigator.share()
if(navigator.share !== undefined) {
    document.addEventListener('DOMContentLoaded', e => {
      var shareBtn = document.querySelector('div.share a');
      shareBtn.addEventListener('click', clickEvent => {
        clickEvent.preventDefault();
        navigator.share({title: document.title, text: window.location.href, url: window.location.href})
          .then(() => console.log('Successful share'),
           error => console.log('Error sharing:', error));
      });
    });
}

Paul Kinlan

Trying to make the web and developers better.

RSS Github Medium