需求:最近公司要做推送,用的是uni-app,這裏備註一下
App.vue裏這樣操作:
分別是iOS 和Android的在線創建推送,以及點擊事件的處理,這裏點擊事件存儲一下,然後發送消息在首頁處理推送。
如果在這裏處理,會有先跳轉推送頁再返回首頁的問題。
plus.push.addEventListener('click', function (msg) { // 存儲一下點擊後的推送信息 // uni.setStorageSync('receive', msg); // 2 處理跳轉 如果沒登錄 去登錄 // const resos = uni.getSystemInfoSync(); // if (resos.platform === 'ios') {} if (!userStore.isLogin) { uni.switchTab({ url: '/pages/autoLogin/index', }); return; } if (msg.aps) { // 離線 到首頁再執行 uni.setStorageSync('msg_payload', msg.payload); uni.$emit('msgPayload'); } else { // 在線可立即執行 但是不行,離線狀態點擊在線推送不行,所以也到首頁再執行 uni.setStorageSync('msg_payload', msg.payload); uni.$emit('msgPayload'); } }); // 在線推送點擊 receive 內創建推送彈窗 uni.onPushMessage(res => { if (res.type == 'click') { console.log('點擊業務在addEventListener處理'); } if (res.type == 'receive') { // 創建推送顯示 // uni.setStorageSync('receive', res); // 創建推送顯示 ios console.log('===onPushMessage======res=============', res); const resos = uni.getSystemInfoSync(); if (resos.platform === 'ios') { var content_obj = JSON.parse(res.data.content); let titleStr = decodeURIComponent(content_obj.title); let contentStr = decodeURIComponent(content_obj.content); uni.createPushMessage({ icon: '', title: titleStr || '連xx', content: contentStr || '您有一個通知', payload: content_obj.url, success: res => { console.log('成功創建', res); }, }); } else { // 創建推送顯示 android let contentStr = decodeURIComponent(res.data.content); uni.createPushMessage({ icon: '', title: res.data.title || '連xx', content: contentStr || '您有一個通知', payload: res.data.payload.url, success: res => { console.log('成功創建', res); }, }); } } plus.runtime.setBadgeNumber(0); }); // 獲取客戶端標識 uni.getPushClientId({ success: res => { let push_clientid = res.cid; uni.setStorageSync('cid', push_clientid); }, }); // #ifdef APP-PLUS let pinf = plus.push.getClientInfo(); if (pinf && pinf.clientid) { uni.setStorageSync('cid', pinf.clientid); } else { var obtainingCIDTimer = setInterval(function () { pinf = plus.push.getClientInfo(); if (pinf.clientid) { uni.setStorageSync('cid', pinf.clientid); clearInterval(obtainingCIDTimer); } }, 50); } // #endif plus.runtime.setBadgeNumber(0);
首頁這樣處理:
如果是離線推送,冷啓動,外部的msgPayload()生效,在線推送的話,
uni.$on('msgPayload', () => { msgPayload(); });
生效。跳轉後,移除存儲的跳轉信息。
onReady(() => { msgPayload(); uni.$on('msgPayload', () => { msgPayload(); }); }); // 不同意隱私 關閉Model function msgPayload() { let payload = uni.getStorageSync('msg_payload'); if (payload && userStore.isLogin) { var redirectUrl = decodeURIComponent(payload); console.log('=離線=======redirectUrl=======', redirectUrl); // 123456 setTimeout(() => { if (isHttpLink(redirectUrl)) { redirectUrl = getJoinSSOUrl(redirectUrl, userStore.token); } if (isTabBarLink(redirectUrl)) { uni.switchTab({ url: redirectUrl, }); } else { jumpSupport(redirectUrl, '1'); } }, 500); setTimeout(() => { uni.removeStorageSync('msg_payload'); }, 1000); } }