Skip to content

Instantly share code, notes, and snippets.

@joshspires
Last active August 12, 2023 07:44
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
Web Share API - A quick and dirty Web Share API implementation that should work across all websites.
<button id="device_shr_btn" style="btn">Share</button>
<script>
document.addEventListener('DOMContentLoaded', function () {
const title = document.title;
const description = document.querySelector('meta[name="description"]').getAttribute('content');
const url = document.location.href;
const shareData = {
title: title,
text: description,
url: url
};
const btn = document.getElementById('device_shr_btn');
btn.addEventListener('click', () => {
navigator.share(shareData);
});
});
</script>
@joshspires
Copy link
Author

joshspires commented Aug 12, 2023

Logic of the code:

  • Title is pulled using document.title, which means whatever is placed between the <title></title> will be used.
  • The description is pulled from the <meta> element the attribute name="description".
  • The URL is pulled from document.location.href.

Not working?

If it seems like the code isn't working with the device you are testing on, it is important to keep in mind that devices handle the Web Share API differently.

Windows

  • Displays the website home URL and the URL of the page being shared.
  • Both the title and text field seem to be ignored.
  • No image is displayed.

Android (tested with Google Pixel)

  • Displays the text (description) and URL of the page being shared.
  • If the text field isn't present, the title is used as a fallback.

MacOS

  • untested

iOS

  • untested

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