You need to enable JavaScript to run this app. Firebase推送通知添加View/Opt-Out动作后无法跳转对应URL如何解决?
优惠活动
大模型
产品
解决方案
定价
更多

Firebase推送通知添加View/Opt-Out动作后无法跳转对应URL如何解决?

代码存在的问题
  • 核心变量未正确取值:onBackgroundMessage回调中的topic、title、body、url等变量没有从接收的推送 payload 中读取,属于未定义变量,实际运行时取不到对应值。
  • 跳转URL作用域失效:notificationclick事件监听的作用域无法访问到onBackgroundMessage回调里定义的url变量,执行跳转时取不到目标地址。
  • 未处理自定义动作逻辑:你添加了view和unsubscribe两个自定义动作,但代码没有对用户点击的动作类型做判断,无法匹配对应交互逻辑。
  • 废弃属性使用:Web Notification API 已不推荐使用click_action属性,自定义跳转逻辑应通过notificationOptions的data字段传递参数实现。
修正后的可运行代码
const messaging = firebase.messaging();
    
messaging.onBackgroundMessage((payload) => {
    console.log('[firebase-messaging-sw.js] Received background message ', payload);
    // 从payload中读取推送携带的参数,根据你实际推送的字段调整路径
    const pushData = payload.data || payload.notification || {};
    const notificationTitle = pushData.title || '新通知';
    const notificationOptions = {
        body: pushData.body || '您收到了一条新消息',
        icon: pushData.icon || '/default-icon.png',
        image: pushData.image,
        badge: pushData.badge,
        // 把跳转URL、退订相关参数存在data字段,点击事件可以读取
        data: {
            targetUrl: pushData.url,
            unsubscribeUrl: pushData.unsubscribe_url // 可提前在推送负载里加退订地址
        },
        actions: [
            {action: 'view', title: 'View'},
            {action: 'unsubscribe', title: 'Opt-Out'}
        ]
    }

    self.registration.showNotification(notificationTitle, notificationOptions);
});

self.addEventListener('notificationclick', function(event) {
    event.notification.close();
    // 读取存在notification里的参数
    const notifyData = event.notification.data;
    // 处理用户点击的动作
    let targetUrl = '';
    switch(event.action) {
        case 'view':
            targetUrl = notifyData.targetUrl;
            break;
        case 'unsubscribe':
            targetUrl = notifyData.unsubscribeUrl;
            break;
        // 点击通知本身默认走view逻辑
        default:
            targetUrl = notifyData.targetUrl;
    }

    event.waitUntil(clients.matchAll({
        type: "window"
    }).then(function(clientList) {
        for (var i = 0; i < clientList.length; i++) {
            var client = clientList[i];
            if (client.url === targetUrl && 'focus' in client) {
                return client.focus();
            }
        }
        if (clients.openWindow) {
            return clients.openWindow(targetUrl);
        }
    }));
});
注意事项
  • 推送时要在负载的data字段中携带url(跳转地址)和unsubscribe_url(退订地址)参数,若你推送的参数名不同,对应修改代码中读取字段的名称即可。
  • 若退订不需要跳转页面,也可以直接在unsubscribe分支中调用后端退订接口,不需要执行跳转逻辑。

内容的提问来源于stack exchange,提问作者Ragnaboy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.13 00:42:01