You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用MinishLink/WebPush发送PWA推送通知时,iOS和Android端始终显示通用通知的问题求助

我现在遇到了一个棘手的问题:我在PWA应用中使用MinishLink/WebPush库发送推送通知,后端基于PHP开发,会把JSON格式的payload发送给浏览器中注册的Service Worker,但iOS和Android端总是显示通用通知内容——明明payload里包含了正确的title和body数据,但最终显示出来的却是“Notifica Generica”和“Hai una nuova notifica.”这类默认文本。

下面是我的相关代码和日志情况:

前端Service Worker代码(sw.js)

self.addEventListener('push', function(event) {
console.log('📩 Evento push ricevuto:', event);

if (!(self.Notification && self.Notification.permission === 'granted')) {
    console.error('❌ Notifiche non supportate o permesso non concesso.');
    return;
}

event.waitUntil(
    Promise.resolve().then(() => {
        let data = {};

        try {
            data = event.data ? event.data.json() : {};
            console.log('✅ Dati JSON ricevuti dal push:', data);
        } catch (error) {
            console.warn('⚠️ Dati ricevuti non in JSON, interpretando come stringa...');
            data = { title: event.data.text(), body: event.data.text() };
        }

        const title = data.title || 'Notifica Generica';
        const options = {
            body: data.body || 'Hai una nuova notifica.',
            icon: data.icon || 'my_icon',
            badge: data.badge || 'my_badge',
            image: data.image || undefined,
            requireInteraction: data.requireInteraction || false,
            data: data.data || {}
        };

        console.log('📢 Mostrando notifica con:', title, options);
        return self.registration.showNotification(title, options);
    }).catch((error) => {
        console.error('❌ Errore durante la visualizzazione della notifica:', error);

        return self.registration.showNotification('Errore', {
            body: 'Non è stato possibile recuperare i dati della notifica.',
            icon: 'my_icon',
            data: { click_action: '/' }
        });
    })
);
});

后端PHP代码

function send_push_notification(
    $title,
    $body,
    $icon = "",
    $image = "",
    $url = "",
    $data = []
) {
    global $wpdb;
    $table_name = $wpdb->prefix . "pwa_push_subscriptions";
    $subscriptions = $wpdb->get_results("SELECT * FROM $table_name");

    if (empty($subscriptions)) {
        pwa_write_log("❌ Nessuna sottoscrizione trovata!");
        return;
    } else {
        pwa_write_log("✅ " . count($subscriptions) . " sottoscrizioni trovate.");
    }

    // Configura le chiavi VAPID
    $auth = [
        "VAPID" => [
            "subject" => "mailto:noreply@nomesito.com",
            "publicKey" => "my_key",
            "privateKey" => "my_key",
        ],
    ];

    $webPush = new WebPush($auth);

    foreach ($subscriptions as $subscription) {
        try {
            $payload_array = [
                "title" => $title,
                "body" => $body,
                "icon" => $icon ?: " my icon",
                "image" => $image ?: null,
                "badge" => "my_badge",
                "requireInteraction" => true,
                "data" => [
                    "click_action" => $url,
                    "url" => $url
                ]
            ];

            $payload = json_encode($payload_array, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

            if (json_last_error() !== JSON_ERROR_NONE) {
                pwa_write_log("❌ Errore nella generazione del JSON: " . json_last_error_msg());
                return;
            }

            $webPush->queueNotification(
                Subscription::create([
                    "endpoint" => $subscription->endpoint,
                    "keys" => [
                        "p256dh" => $subscription->public_key,
                        "auth" => $subscription->auth_key,
                    ],
                ]),
                $payload
            );
        } catch (Exception $e) {
            pwa_write_log("❌ Errore nell'invio della notifica: " . $e->getMessage());
        }
    }

    foreach ($webPush->flush() as $report) {
        $endpoint = $report->getRequest()->getUri();
        if ($report->isSuccess()) {
            pwa_write_log("✅ Notifica inviata con successo a {$endpoint}");
        } else {
            pwa_write_log("❌ Errore nell'invio della notifica a {$endpoint}: " . $report->getReason());
        }
    }
}

日志情况

日志显示WebPush库初始化正常,Composer也安装正确,推送通知发送成功,但客户端就是不显示自定义的title和body,而是用了代码里的默认值。

我该怎么解决这个问题呢?感谢各位的帮助!

备注:内容来源于stack exchange,提问作者Cristian

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 08:38:06