Angular 5中如何基于@angular/service-worker处理PHP后端Web推送的action点击
Got it, let's break down how to make notification click actions (both the notification itself and its action buttons) open specific pages in your Angular 5 app using the official service worker. Here's a step-by-step solution:
1. Create a Custom Service Worker Script
Angular's generated service worker doesn't handle notificationclick out of the box, so we'll add a custom script to extend its functionality. Create a file named custom-sw.js in your project's src folder:
self.addEventListener('notificationclick', (event) => { // First, close the notification popup event.notification.close(); // Determine the target URL: use the action button's value, or fallback to the notification's data url const targetUrl = event.action || event.notification.data.url; if (targetUrl) { // Use the Clients API to either focus an existing tab or open a new one event.waitUntil( clients.matchAll({ type: 'window', includeUncontrolled: true }) .then(clientList => { // Check if the target page is already open in a tab for (const client of clientList) { if (client.url === targetUrl && 'focus' in client) { return client.focus(); } } // If no existing tab, open a new one if (clients.openWindow) { return clients.openWindow(targetUrl); } }) ); } });
2. Update Your ngsw-config.json
Tell Angular's service worker to import your custom script. Add an importScripts array at the top of your ngsw-config.json (in the src folder):
{ "importScripts": ["/custom-sw.js"], "index": "/index.html", "assetGroups": [ // Keep your existing asset group configurations here ] }
3. Ensure the Custom Script is Bundled
Add custom-sw.js to your Angular CLI assets so it gets copied to the dist folder during build. Open angular-cli.json (Angular 5 uses this instead of angular.json) and update the assets array:
"assets": [ "assets", "favicon.ico", "custom-sw.js" ]
4. Send the Right Payload from Your PHP Backend
Make sure your push notification payload includes the necessary action/data fields. For example:
{ "notification": { "title": "New Update", "body": "Check out our latest content!", // Action buttons (optional) "actions": [ { "action": "/latest-content", "title": "View Now" }, { "action": "/profile", "title": "Go to Profile" } ], // Fallback URL for when users click the notification itself (not an action button) "data": { "url": "/home" } } }
Key Notes
- HTTPS Requirement: Service Workers (and push notifications) require HTTPS in production (localhost is exempt for testing).
- Relative vs Absolute URLs: Use absolute URLs if your app is hosted on a subdomain, or ensure relative paths are rooted to your app's base URL.
- Testing: Run
ng build --prodand serve thedistfolder with an HTTPS server to test the full flow.
内容的提问来源于stack exchange,提问作者Opemipo Bolaji

