- 有個(gè)需求,通過接口獲取第三方給頁面,由于第三方的頁面隨時(shí)會(huì)變,所有不好讓APP原生寫死,便通過h5寫一個(gè)空白頁面,獲取到第三方頁面后跳轉(zhuǎn)。
其中碰到兩個(gè)問題
安卓跳轉(zhuǎn)第三方頁面后,點(diǎn)擊返回,會(huì)返回到我的空白頁面,然后再次跳轉(zhuǎn)到第三方頁面
ios返回我的空白頁面不會(huì)觸發(fā)reload事件
- 對(duì)于第一個(gè)問題,我是通過url處理,APP開始進(jìn)入我的頁面時(shí),會(huì)帶參數(shù),然后
history.pushState方法把參數(shù)去掉,這樣,當(dāng)安卓返回我的頁面后,我通過url參數(shù)判斷是返回還是首次進(jìn)入處理。 - 第二個(gè)問題,ios返回不會(huì)重新刷新頁面,通過監(jiān)聽
pageshow事件,在該事件中處理返回的事件。
代碼如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport"
content="width=device-width, height=device-height, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
<meta name="format-detection" content="telephone=no">
<title></title>
</head>
<body>
</body>
<script>
var u = navigator.userAgent
var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1
var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)
// 用于app 中轉(zhuǎn)跳 第三方
var hash = location.hash
// ios返回上一頁面不會(huì)刷新
if (isiOS) {
window.onload = function () {
var isPageHide = false;
window.addEventListener('pageshow', function () {
if (isPageHide) {
// 自家APP封裝的關(guān)閉容器方法
window.webkit.messageHandlers.NativeFunction.postMessage(JSON.stringify({
'command': 'closePageAction',
'parameter': ''
}))
}
});
window.addEventListener('pagehide', function () {
isPageHide = true;
});
}
}
// 首次進(jìn)入
if (hash) {
// 去掉 url上帶的參數(shù)
history.pushState({}, '', location.origin + location.pathname)
} else {
// ios不會(huì)進(jìn)入這里
if (isAndroid) {
// 調(diào)用自家APP封裝的 方法 同意后關(guān)閉容器
window.jsobj.NativeFunction(JSON.stringify({
'command': 'agree'
}))
}
}
// 接口獲取第三方頁面 并跳轉(zhuǎn)
var ajax = new XMLHttpRequest();
ajax.open('get', '/getgroup');
ajax.send();
ajax.onreadystatechange = function () {
if (ajax.readyState == 4 && ajax.status == 200) {
var res = JSON.parse(ajax.response)
if (res.code == 0) {
// 接口通過hash 跳轉(zhuǎn)不同頁面
res.data.forEach(function (item) {
if (item.agreementCode == 'tk_customerprivacy_agreement' && hash == '#1') {
window.location.href = item.agreementUrl
return false
}
if (item.agreementCode == 'tk_customerservice_agreement' && hash == '#2') {
window.location.href = item.agreementUrl
return false
}
})
}
}
}
</script>
</html>