Skip to content

Instantly share code, notes, and snippets.

@deanhume
Created February 22, 2017 21:34
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save deanhume/8215074871ff2a56a85963dc202e38c3 to your computer and use it in GitHub Desktop.
Save deanhume/8215074871ff2a56a85963dc202e38c3 to your computer and use it in GitHub Desktop.
Web Share API example
var shareButton = document.getElementById('shareThis');
var supported = document.getElementById('support');
// Listen for any clicks
shareButton.addEventListener('click', function (ev) {
// Check if the current browser supports the Web Share API
if (navigator.share !== undefined) {
// Get the canonical URL from the link tag
var shareUrl = document.querySelector('link[rel=canonical]') ? document.querySelector('link[rel=canonical]').href : window.location.href;
// Share it!
navigator.share({
title: document.title,
url: shareUrl
}).then(() => console.log('Successful share'))
.catch((error) => console.log('Error sharing:', error));
ev.preventDefault();
} else {
supported.innerHTML = "Unfortunately, this feature is not supported on your browser";
}
});
@rajatjasuja23
Copy link

hi,any idea how to call the share in new tab, for example if i click on fb or google plus then it should link to new tab ,right now its opening pop up for me which is stoping my other functionalities

@shgysk8zer0
Copy link

@rajatjasuja23 Are you using some poorly written shim for this?

I know that Chrome has the beginnings of an implementation on Desktop that opens an empty window (presumably services may be added somehow at some point, or maybe some OS integration on Windows 10). On Android, it uses the native sharing feature.

At least for Android, opening a popup window or tab just does not apply. They open in apps. If you want to open a tab or window in the browser, you're missing the entire point of the API. And the process is async (Promises), so use of navigator.share should not interfere with any other JS unless you're using await navigator.share().

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment