On this page
A navigator.share button can offer the current page to a device’s share interface, but window.location.href is not always the URL you want to send. It may include tracking parameters, temporary state, or information specific to the current user.
This tutorial shows how to choose a page URL, share it with a title and optional text, and provide a usable fallback when native sharing is unavailable.
Key Takeaways
- Choose the URL deliberately: removing the query string and fragment is useful only when the remaining path still identifies the intended page.
- Call
navigator.share()directly from a user action, such as a button click, in a secure context. - Feature-detect the API and keep a copyable link available. A completed share call does not prove that a recipient received anything.
- Test on the browsers and devices you support. Browser documentation was not available to consult for this article, and the example below was not executed.
Advertisement
Choose the URL before sharing
A browser address has several components. For example, in https://example.com/products/hat?color=blue#details, the path is /products/hat, the query is color=blue, and the fragment is details.
Those components can serve different purposes:
- Path: Often identifies the page, but can itself contain private or user-specific information.
- Query: May contain a useful selection, such as a product variant, or unwanted values, such as tracking parameters or temporary state.
- Fragment: Often identifies a section or client-side state. Removing it may change what the recipient sees.
A URL parser can help you inspect these components. It cannot invoke the Web Share API or tell you what a recipient received.
For a simple public page whose identity is entirely in its path, you can remove the query and fragment:
function getShareUrl() {
const url = new URL(window.location.href);
url.search = "";
url.hash = "";
return url.href;
}
This is a policy choice, not a general canonicalization algorithm. If your app uses a query value or fragment to identify the page, preserve the necessary values explicitly instead. If the current path is private, a preview route, or an alias, obtain the appropriate public URL from trusted application data. Make sure the page is actually accessible to intended recipients; sharing a link does not grant access.
Avoid putting credentials, access tokens, personal data, or other secrets in share URLs. Review the title and optional text too: either can reveal information that should not leave the page.
Share the page with a fallback
The following standalone example is for a public page whose path is the intended share URL. Save it as an HTML file and serve it from your application. Use HTTPS for realistic device testing; some browsers also treat localhost as a secure context for development. Replace the sample title and text with content appropriate to your page.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Example public page</title>
</head>
<body>
<h1>Example public page</h1>
<button id="share" type="button">Share page</button>
<p>Or copy the link:</p>
<label for="share-url">Page URL</label>
<input id="share-url" type="text" readonly>
<button id="copy" type="button">Copy link</button>
<p id="status" role="status"></p>
<script>
const shareButton = document.querySelector("#share");
const copyButton = document.querySelector("#copy");
const urlInput = document.querySelector("#share-url");
const status = document.querySelector("#status");
function getShareUrl() {
const url = new URL(window.location.href);
url.search = "";
url.hash = "";
return url.href;
}
function updateLink() {
const url = getShareUrl();
urlInput.value = url;
return url;
}
updateLink();
const canUseShare = window.isSecureContext &&
typeof navigator.share === "function";
if (!canUseShare) {
shareButton.disabled = true;
status.textContent =
"Native sharing is unavailable here. Copy the link instead.";
}
shareButton.addEventListener("click", async () => {
const data = {
title: document.title,
text: "Take a look at this page.",
url: updateLink()
};
try {
// Invoke share directly from the click; do not await other work first.
await navigator.share(data);
status.textContent =
"The share action completed; recipient delivery is not confirmed.";
} catch (error) {
if (error && error.name === "AbortError") {
status.textContent =
"Sharing was canceled or no share target was available.";
} else {
status.textContent =
"Could not open sharing. Copy the link below instead.";
}
}
});
copyButton.addEventListener("click", async () => {
const url = updateLink();
try {
if (!navigator.clipboard ||
typeof navigator.clipboard.writeText !== "function") {
throw new Error("Clipboard API unavailable");
}
await navigator.clipboard.writeText(url);
status.textContent = "Link copied.";
} catch (error) {
urlInput.focus();
urlInput.select();
status.textContent =
"Copy was unavailable. Copy the selected link manually.";
}
});
</script>
</body>
</html>
The share payload contains a URL, a title, and optional text. The receiving app decides how to use them, so their presentation can vary. The browser or operating system may show a share interface; the example does not automatically post or send content. The user chooses whether to continue.
Feature detection only establishes that a method is present, not that every sharing attempt will succeed. The call can still fail or be canceled, so the selectable URL remains available. Clipboard access can also fail; the fallback selects the link for manual copying.
Advertisement
Check behavior on your target devices
The example has not been run or checked against current browser documentation in this article. Before publishing a compatibility statement, consult current MDN and browser-vendor documentation for your target environments, including secure-context and user-activation requirements. Then test the actual application on supported browsers and devices.
Use this manual checklist:
- Native sharing available: Open the page in a secure context, tap Share, and check that the proposed URL, title, and text are appropriate. Cancel and confirm that the page remains usable.
- Native sharing unavailable: Use a browser or environment without the method. Confirm that the share button is disabled and that the URL can still be copied or selected manually.
- Share fails: Where practical, test a device without an available share target or simulate a rejected call in your application tests. Confirm that the fallback remains usable.
- Clipboard unavailable or denied: Confirm that the URL field can be selected and copied manually.
- URL policy: Add a test query and fragment to the page address. Confirm that dropping them produces the intended public page, then check any routes that require a query value or fragment.
- Recipient access: Open the selected URL in a separate browser session without the sender’s login. Confirm that it leads to the intended page or an appropriate access prompt.
A development URL such as localhost is useful for checking interface behavior, but it generally will not identify the same page on a recipient’s device. Use a reachable test deployment when checking a real handoff.
Common Mistakes
- Sharing the address bar blindly. Query values and even paths may expose temporary or user-specific information.
- Stripping every parameter without checking the app. A query value or fragment may identify the content the user intended to share.
- Awaiting unrelated work before calling
navigator.share(). User activation is time-sensitive; prepare share data in advance or synchronously in the click handler. - Treating a resolved promise as proof of delivery. The application does not necessarily know what the recipient received or did with the content.
- Assuming clipboard access always works. Keep the URL visible and manually selectable.
Best Practices
Define a share-URL policy for each type of page: use trusted public URLs where available, and preserve only the state needed to identify the intended content. Keep the native-share call directly connected to a user gesture, handle rejection without treating cancellation as a successful send, and test the fallback independently. Check current documentation and real target devices before making support claims.
Conclusion
A useful share button starts with the right public URL, not necessarily the current address bar. Combine an explicit URL policy with a user-initiated native share action and a selectable-link fallback.
What would your domain sell for?
A free TidyURLs account unlocks the Domain Estimator. It prices a name from 191,011 real domain sales.