On this page
A notification can contain the right URL and still open the wrong page if the service worker focuses an existing window without navigating it, the app redirects to login, or the installed app handles the route differently from a browser tab. If a PWA notification click opens the wrong page, test the full path from notification data to the final rendered route on each installed-device configuration you support.
Key Takeaways
- A service worker must explicitly decide whether to focus an existing window, navigate it, or open a new one.
- Validate notification targets against your own origin and approved routes before navigation. A same-origin URL is not necessarily an authorized destination.
- Test with the app open, closed, signed in, and signed out; a successful window-opening call does not prove the intended page rendered.
- Use a safe fallback route and let the app or server handle missing pages and authentication.
- Browser support and the code below were not verified in this environment. Check current documentation and test on your actual devices before release.
How notification clicks choose a page
For a notification created by a service worker, the worker can listen for notificationclick. The notification's data can carry a target URL. Inside the handler, event.waitUntil() keeps the asynchronous work associated with the event: closing the notification, looking for window clients, navigating an appropriate client, focusing it, or opening a new window.
These operations are different:
- Focus brings an existing window forward; it does not by itself change its route.
- Navigate asks an existing window to load a URL. It may replace the current page and discard unsaved state.
- Open a window requests a new browsing context. The browser or operating system controls how that appears, and the request can fail or return no client.
An app can also redirect after navigation. For example, a protected route may send a signed-out user to login. Investigate the final rendered route, not just the URL stored in notification data.
Advertisement
Validate and route a click
The following illustrative handler assumes the app is served from the same origin under /app/, and that the existing service worker is configured for that app. Add it to that worker rather than registering a second worker solely for this example. The deployment must serve the app and its fallback route at /app/.
This policy permits only three paths. It also permits one optional item parameter on the inbox route. Adapt the allowlist and parameter rules to your app; a rejection deliberately goes to /app/ instead of trying to repair an untrusted URL. The example has not been executed here.
const appHome = new URL('/app/', self.location.origin);
const allowedPaths = new Set(['/app/', '/app/inbox', '/app/account']);
function notificationTarget(raw) {
if (typeof raw !== 'string' || raw.length > 2048) return appHome.href;
try {
const url = new URL(raw, appHome);
if (
url.origin !== appHome.origin ||
url.username ||
url.password ||
url.hash ||
!allowedPaths.has(url.pathname)
) {
return appHome.href;
}
const entries = [...url.searchParams.entries()];
if (entries.length > 0) {
const validItem =
url.pathname === '/app/inbox' &&
entries.length === 1 &&
entries[0][0] === 'item' &&
/^[A-Za-z0-9_-]{1,64}$/.test(entries[0][1]);
if (!validItem) return appHome.href;
}
return url.href;
} catch {
return appHome.href;
}
}
self.addEventListener('notificationclick', (event) => {
event.notification.close();
event.waitUntil((async () => {
const target = notificationTarget(event.notification.data?.url);
const windows = await self.clients.matchAll({
type: 'window',
includeUncontrolled: true,
});
// Client.url may not reflect a client-side router's current view.
const existing = windows.find((client) => {
const url = new URL(client.url);
return url.origin === appHome.origin && url.pathname.startsWith('/app/');
});
if (existing) {
let navigated = null;
try {
navigated = await existing.navigate(target);
} catch (error) {
console.error('Could not navigate existing app window', error);
}
if (navigated) {
// Do not open a duplicate if focus fails after navigation succeeds.
await navigated.focus();
return;
}
}
const opened = await self.clients.openWindow(target);
if (!opened) console.warn('The browser did not return an opened window');
})().catch((error) => {
console.error('Notification click handling failed', error);
}));
});
When creating a notification with the service worker's showNotification(), put the intended route in its data, for example { url: '/app/inbox?item=message_42' }. Ensure the value corresponds to your validated route policy. Do not put credentials or other sensitive information in notification text or URLs.
This implementation prefers an existing matching app window and navigates it, even if another app window might be a better match. includeUncontrolled can expose same-origin windows outside the worker's control, so the example filters for the app path. If your app supports multiple windows or workspaces, define an explicit selection policy. For a single-page app, Client.url may not reflect its current client-side route; coordinate with the page if you need to select a window by in-app state. Messaging introduces its own timing and failure cases, so retain a fallback.
Same-origin boundaries and fallback behavior
Restricting destinations to your origin prevents a notification payload from directly choosing an arbitrary external URL in this handler. The route allowlist adds a narrower boundary, but neither check grants permission to view a resource. The server and app must still enforce authentication and authorization, including authorization for an inbox item.
The handler cannot determine from a successful navigation whether the server returned a missing page, the app failed to render, or an allowed route redirected elsewhere. Configure the server and app to handle unavailable routes with a useful not-found page or a safe app-home link. Review redirects separately: validating the initial URL does not guarantee that its eventual destination remains on the same origin.
If a protected route requires login, preserve the intended destination only through a validated, same-origin return path. After login, validate it again and check the user's authorization before showing the resource. If the resource is gone or access is denied, show an appropriate message and a safe way back to the app.
Advertisement
Test on installed devices
First, record the notification payload, the expected final route, the device and operating system, browser, installed-app state, and authentication state. Send a notification through the same creation and delivery path you intend to ship. Grant notification permission through the normal user flow, then tap the actual notification; invoking the handler in isolation is not a substitute for this test.
| Scenario | Setup and action | What to verify |
|---|---|---|
| Installed PWA | Install the app, then tap a notification for an allowed route. | The app opens in the expected context and renders the intended route, including any permitted parameter. |
| Open app window | Leave the app on a different page, then tap the notification. | The selected window navigates rather than merely receiving focus. Check whether navigation discards unsaved work. |
| Closed app | Close the app, send a fresh notification, and tap it. | A window opens and the final route loads. Repeat after the app has been inactive, since worker and app lifecycle behavior can differ. |
| Authentication required | Tap a protected-route notification while signed in, then repeat while signed out. | Authorized users reach the route; signed-out users get a login flow and, after login, an authorized return or a clear fallback. |
| Invalid or unavailable target | Try an external URL, a disallowed path, an invalid parameter, and a valid route whose resource is missing. | Invalid targets reach the safe fallback. Missing or forbidden resources show an appropriate in-app or server response. |
Repeat for each supported device, operating system, browser, and installation method. Also check multiple open app windows, offline or poor-network conditions, expired sessions, notification permission denial, and notification action buttons if your app uses them. If the app is already open, confirm whether opening a new window is acceptable or whether your product requires reuse.
Diagnose a wrong destination
- Check notification data. Confirm that
data.urlis present and represents the intended route. Avoid logging full URLs if their query strings can contain sensitive data. - Check validation. Determine whether the URL was accepted or replaced by the fallback. In development, log a reason code rather than private payload contents.
- Check window selection. Determine whether the handler found an existing client and whether navigation and focus succeeded. A focused old page usually points to missing or failed navigation.
- Check redirects and app routing. Inspect the final location and app state. A login redirect, missing server-side route handling, stale app code, or client-side routing error can change the result after the click handler runs.
- Check the deployed worker. Confirm that the intended worker and click handler are active for the installed app, and test after an update as well as on a clean installation.
Common Mistakes
- Focusing the first window and assuming it will display the notification target.
- Testing only in a normal browser tab rather than an installed app on the supported devices.
- Trusting a payload URL merely because it parses, or treating same-origin validation as authorization.
- Assuming
openWindow()ornavigate()guarantees a successful page load. - Losing the intended destination during login, or accepting an unrestricted return URL afterward.
- Putting access tokens, personal data, or private message contents in URLs that may be logged or retained.
Best Practices
Keep the navigation policy explicit: choose which window to reuse, which routes and parameters are allowed, and what happens when navigation fails. Instrument failures without recording sensitive URLs. Provide a useful app-home or not-found experience, and test the final rendered state rather than only the notification handler.
Before publication, consult the current MDN Service Worker API and Notifications API documentation and verify browser and operating-system support for notification clicks, window opening, and your installation flow. Those sources and current support could not be checked in this environment; do not treat this article as a compatibility guarantee.
Conclusion
A reliable notification click requires more than a valid-looking URL. Validate the target, deliberately select and navigate a window, and verify the final route—including login and failure paths—on every installed-device configuration you support.
What would your domain sell for?
A free TidyURLs account unlocks the Domain Estimator. It prices a name from 191,011 real domain sales.