h5實現自動跳轉到指定頁面的小程式
阿新 • • 發佈:2022-05-19
進入h5頁面自動跳轉到小程式的條件,必須要後端返回跳轉地址,具體使用方法可以參考開發文件
前端需要判斷使用者是否在微信內,並且獲取跳轉需要的引數,進行介面呼叫和小程式跳轉
<html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>測試</title> </head> <body> <div id="app" class="app"> <div id="wechat-container"> </div> </div> <script> // 獲取連線中的search function getQueryVariable(variable) { var url = window.location.href.substring(window.location.href.indexOf('?')); var theRequest = new Object(); if (url.indexOf("?") != -1) { var str = url.substr(1); strs = str.split("&"); for (var i = 0; i < strs.length; i++) { theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]); } } return theRequest[variable] || false; } function docReady(fn) { if (document.readyState === 'complete' || document.readyState === 'interactive') { fn() } else { document.addEventListener('DOMContentLoaded', fn); } } docReady(async function () { const ua = navigator.userAgent.toLowerCase(); // 瀏覽器ua識別型別 const isWXWork = ua.match(/wxwork/i) == 'wxwork'; // 判斷是否有微信執行緒 const isWeixin = !isWXWork && ua.match(/micromessenger/i) == 'micromessenger'; // 是否是微信瀏覽器 // 判斷是否是桌面瀏覽器 let isDesktop = false if (!navigator.userAgent.match( /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|IEMobile)/i)) { isDesktop = true } if (isDesktop) { var cu = document.getElementById('wechat-container'); cu.innerHTML = '<div class="app-btn">請在手機微信裡掃碼訪問</div>'; // alert("請用手機開啟") } else if (isWeixin) { getScheme(); } else { var cu = document.getElementById('wechat-container'); cu.innerHTML = '<div class="app-btn">請在手機微信裡掃碼訪問</div>'; } }); // 外鏈 function getScheme() { let addr = getQueryVariable('addr'); const url = 'https:/XXX/url_scheme' const xhr = new XMLHttpRequest(); xhr.open('POST', url, true); xhr.setRequestHeader("Content-type", "application/json"); let jumpQuery = 'code%3D' + addr; // 引數 let query = { jumpPath: '/pages/index/index', // 需要跳轉的小程式頁面 jumpQuery: jumpQuery // 傳入小程式頁面的引數 } xhr.send(JSON.stringify(query)); xhr.onreadystatechange = function () { if (xhr.readyState == 4 && xhr.status == 200) { let data = JSON.parse(xhr.responseText).data; let status = JSON.parse(xhr.responseText).status; if (status === 0) { location.href = data.openLink; // 跳轉到後端返回的小程式地址 如weixin://dl/business/?t=NX8lFDmrCnf } else { alert(JSON.parse(xhr.responseText).msg) } } } } </script> </body> </html>