On this page
When a web protocol handler link opens the wrong page, the problem may be registration, URL encoding, handler routing, or the destination chosen by your app. This tutorial walks through a small example that registers a custom scheme, decodes the incoming link, and presents a validated HTTPS destination.
The example has not been executed, and browser documentation and compatibility could not be checked in this run. Verify the registration API, browser behavior, and installed-app behavior in the browsers and environments you intend to support.
Key Takeaways
- A custom-scheme link invokes a registered handler; an ordinary HTTPS link does not automatically invoke that handler.
- The handler receives the whole custom URL through a
%splaceholder. Parse the outer handler query and then the custom URL rather than manually decoding everything at once. - Registration, user approval, and whether a link opens in an installed PWA window depend on the browser and environment. Test the actual launch path.
- Validate destinations and offer a normal HTTPS link as a fallback. Do not put secrets in either URL.
How the link reaches the handler
The example uses a custom URL such as:
web+tidylink:open?target=https%3A%2F%2Fexample.com%2Fguide
A registration points the browser to a same-origin handler template such as /handle/?url=%s. When the browser invokes that handler, it substitutes the encoded custom URL for %s. The handler page reads its url parameter, parses the custom URL, and extracts target from that URL's query.
There are two distinct encoding layers. The target is encoded inside the custom URL, and the entire custom URL is encoded for insertion into the handler URL. URLSearchParams handles one query layer at a time; calling decodeURIComponent again on the returned value can corrupt valid percent-encoded data or throw on malformed input.
This example allows navigation only to https://example.com. Replace that origin with a destination you control before adapting the pattern. An origin allowlist does not protect against an open redirect hosted on an allowed origin.
Advertisement
Register the handler and provide a fallback
Serve the following as an HTML page from an HTTPS origin you control. Configure that server to serve the handler page in the next section at /handle/. The registration API is available only in supporting browsers and is subject to browser security rules and user choice; a successful API call does not prove that the user accepted the handler or that it will open in an installed app.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Protocol handler example</title>
</head>
<body>
<button id="register" type="button">Register link handler</button>
<p id="status" role="status"></p>
<p>
<a href="web+tidylink:open?target=https%3A%2F%2Fexample.com%2Fguide">
Open the guide with the registered handler
</a>
</p>
<p>
<a href="https://example.com/guide">Open the guide directly instead</a>
</p>
<script>
const status = document.querySelector('#status');
const register = document.querySelector('#register');
if (typeof navigator.registerProtocolHandler !== 'function') {
register.disabled = true;
status.textContent = 'Protocol registration is unavailable here. Use the direct link.';
} else {
register.addEventListener('click', () => {
try {
navigator.registerProtocolHandler('web+tidylink', '/handle/?url=%s');
status.textContent = 'Registration requested. Follow any browser prompt, then test the link.';
} catch (error) {
status.textContent = 'Registration could not be requested. Use the direct link.';
console.error(error);
}
});
}
</script>
</body>
</html>
The web+ prefix and lowercase ASCII suffix are used for a custom scheme. Keep %s in the handler template: it is the placeholder for the incoming URL. The handler must satisfy the browser's registration restrictions; this example uses a same-origin HTTPS page and makes the request in response to a button click. Browsers may prompt, decline, or manage existing registrations differently.
The direct HTTPS link remains usable when the API is absent, registration is declined, or the operating system does not route the custom link as expected. Feature detection alone cannot tell you whether the handler has been approved or selected.
Parse and validate the incoming URL
Serve this page at /handle/. It shows a destination link only after validation; it does not automatically redirect. That extra click makes the destination visible to the user before navigation.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="referrer" content="no-referrer">
<title>Open a registered link</title>
</head>
<body>
<h1>Open a registered link</h1>
<p id="message" role="status"></p>
<a id="destination" hidden rel="noreferrer">Continue to the guide</a>
<script>
const message = document.querySelector('#message');
const destination = document.querySelector('#destination');
try {
const handlerUrl = new URL(window.location.href);
const incomingValues = handlerUrl.searchParams.getAll('url');
if (incomingValues.length !== 1 || incomingValues[0].length > 4096) {
throw new Error('Expected one reasonably sized incoming URL.');
}
const incoming = new URL(incomingValues[0]);
if (incoming.protocol !== 'web+tidylink:' || incoming.pathname !== 'open') {
throw new Error('Unexpected custom link.');
}
const targets = incoming.searchParams.getAll('target');
if (targets.length !== 1) {
throw new Error('Expected exactly one target.');
}
const target = new URL(targets[0]);
if (
target.protocol !== 'https:' ||
target.origin !== 'https://example.com' ||
target.username !== '' ||
target.password !== ''
) {
throw new Error('Destination is not allowed.');
}
destination.href = target.href;
destination.textContent = `Continue to ${target.href}`;
destination.hidden = false;
message.textContent = 'Check the destination before continuing.';
} catch (error) {
message.textContent = 'This link is invalid or its destination is not allowed.';
console.error(error);
}
</script>
</body>
</html>
new URL() rejects many malformed or relative values, and the explicit checks reject a missing or duplicated target, a different scheme or path, credentials, and destinations outside the allowed origin. URL parsers can normalize some inputs rather than reject them, so add application-specific path and query rules if the handler should accept only particular pages. The length limit is an example application limit, not a browser limit.
Advertisement
Test the complete launch path
- Deploy both pages to an HTTPS test origin you control. Confirm
/handle/serves the handler page rather than a server error or unrelated app route. - Select Register link handler and respond to any browser prompt. If no prompt appears or the link goes elsewhere, inspect the browser's protocol-handler settings and any competing registrations.
- Select the custom link. The handler should offer a link to
https://example.com/guide; select that link to continue. If it does not, inspect the handler page'surlquery parameter and parse each layer separately. - Try missing and duplicate
targetparameters, an invalid target, a non-HTTPS target, and a different origin in links you construct for your own test environment. The handler should show its error message rather than offer a destination. - Try the direct HTTPS fallback without registering the handler. Repeat the custom-link test in each supported browser and operating system, both with and without the PWA installed. Record whether the handler opens in a browser tab or an app window; do not assume registration controls the window type.
Also test a target containing its own query parameters: encode the entire target as the custom link's target value so its & characters do not become parameters of the custom URL. If a service worker or client-side router controls /handle/, check that its cached response and routing preserve the handler query string.
Common Mistakes
- Testing only an HTTPS link. Registration for
web+tidylink:does not establish interception of ordinary HTTPS navigation. - Decoding twice. Parse the handler query first, then parse the resulting custom URL and its target parameter. Avoid blanket manual decoding.
- Assuming registration means consent. A request can be rejected or a different handler can be selected. Keep the direct link available and explain what registration does.
- Redirecting to any supplied target. An unrestricted handler can become an open redirect. Validate the destination and, where needed, restrict paths as well as origins.
- Putting secrets in URLs. Handler URLs and destinations can appear in history, server or proxy logs, and other browser surfaces. The referrer policy in the example limits one potential disclosure path; it does not make URL-carried secrets safe.
Best Practices
Use fictional, non-sensitive values in test links. Make the registration action explicit, describe what users should expect, and let them choose the HTTPS fallback. Validate incoming values even if your own app generated the link: anyone can construct a custom URL.
This example performs client-side navigation, not a server-side fetch. If a later implementation fetches user-provided destinations on the server, URL parsing and an origin check alone are not complete SSRF defenses; enforce appropriate network and redirect restrictions as well.
Conclusion
Test registration, nested URL parsing, destination validation, and the direct fallback as separate steps. Before launch, verify compatibility and installed-window behavior on the actual browser and operating-system combinations your users rely on.
What would your domain sell for?
A free TidyURLs account unlocks the Domain Estimator. It prices a name from 191,011 real domain sales.