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

OneSignal推送通知消失后无法找回,已实现列表拉取仍存问题求助

解决OneSignal通知消失后无法查看的问题

嘿,你已经迈出了最关键的一步——成功用PHP拉取到通知列表了!接下来咱们就把这些通知在前端展示出来,让用户随时能查看历史通知,完美解决通知消失找不到的问题。

第一步:确保你的PHP接口返回JSON格式

首先得调整下你的PHP文件,让它返回标准的JSON数据,这样前端才能轻松解析。在PHP文件末尾加上这段代码:

header('Content-Type: application/json');
echo json_encode($notification_list); // $notification_list是你拉取到的通知数组

另外别忘了,拉取通知需要指定当前用户的OneSignal ID,所以得让前端把用户ID传给PHP——后面会说怎么在前端获取这个ID。

第二步:用HTML+JavaScript展示通知列表

因为你熟悉HTML,咱们用最简单的方式实现。把这段代码加到你现有的应用页面里就行:

<!-- 通知历史展示容器 -->
<div id="notification-history">
  <h3>我的通知</h3>
  <div id="notifications-list"></div>
  <div id="loading-status">加载中...</div>
</div>

<script>
// 先通过OneSignal SDK获取当前用户的ID
OneSignal.User.getUserId().then(function(userId) {
  // 请求你的PHP接口,带上用户ID参数
  fetch('你的PHP文件路径.php?user_id=' + userId)
    .then(response => response.json())
    .then(data => {
      const listContainer = document.getElementById('notifications-list');
      const loading = document.getElementById('loading-status');
      loading.style.display = 'none'; // 隐藏加载提示

      // 处理空通知的情况
      if (data.length === 0) {
        listContainer.innerHTML = '<p>暂无历史通知</p>';
        return;
      }

      // 遍历通知数据,生成列表项
      let notificationsHtml = '';
      data.forEach(notification => {
        // 这里的字段要和OneSignal返回的对应,一般是title(标题)、body(内容)、created_at(创建时间)
        notificationsHtml += `
          <div class="notification-item">
            <h4>${notification.title}</h4>
            <p>${notification.body}</p>
            <small>${new Date(notification.created_at).toLocaleString()}</small>
          </div>
        `;
      });

      listContainer.innerHTML = notificationsHtml;
    })
    .catch(error => {
      console.error('加载通知失败:', error);
      document.getElementById('loading-status').textContent = '加载失败,请稍后重试';
    });
});
</script>

<style>
/* 简单美化下通知样式,你可以根据自己的应用风格调整 */
.notification-item {
  border-bottom: 1px solid #eee;
  padding: 12px 0;
  margin-bottom: 10px;
}
.notification-item h4 {
  margin: 0 0 6px 0;
  color: #2d3748;
}
.notification-item p {
  margin: 0 0 6px 0;
  color: #4a5568;
}
.notification-item small {
  color: #718096;
}
</style>

几个关键注意点

  • 把代码里的你的PHP文件路径.php替换成你实际的PHP文件地址。
  • 确保OneSignal的SDK已经在你的页面里正确加载了,不然OneSignal.User.getUserId()会报错。
  • 检查PHP接口里是否正确使用了传过来的user_id参数,拉取该用户专属的通知列表。

这样用户就能在应用里看到一个专属的通知历史板块,随时找回之前收到的推送啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:07:50