從h5跳到App可以使用URL Scheme協(xié)議解決解阅。該協(xié)議還可以解決以下幾個問題:
- 從App內(nèi)部瀏覽器頁面跳轉(zhuǎn)到App原生頁面
- 外部瀏覽器跳轉(zhuǎn)到自己的App,并可以指定頁面
- APP跳轉(zhuǎn)到另一個APP指定頁面
- 通過短信中的URL打開原生APP
協(xié)議格式
{scheme}://{host}:{port}/{path}?{query}
備注 | |
---|---|
scheme | 協(xié)議漆腌, 跟app開發(fā)獲取 |
host | 域名 |
port | 端口 |
path | 路徑嚎尤,跳轉(zhuǎn)的具體位置映皆,如果不設(shè)置遥倦,則默認(rèn)打開用戶之前停留的頁面或首頁 |
query | 參數(shù)荷荤,跳轉(zhuǎn)時需要攜帶的參數(shù) |
使用方式
- 其他app內(nèi)置瀏覽器睦霎。如微信內(nèi)置瀏覽器、qq內(nèi)置瀏覽器累魔、微博內(nèi)置瀏覽器摔笤,建議識別后引導(dǎo)用戶跳轉(zhuǎn)至瀏覽器App, 再進(jìn)行下一步操作。
// 是否是微信瀏覽器
export const isWeixin = () => {
const userAgent: any = window.navigator.userAgent.toLowerCase()
return userAgent.match(/MicroMessenger/i) == 'micromessenger'
}
// 是不是qq
export const isQQ = () => {
const userAgent = window.navigator.userAgent.toLowerCase()
const androidBrowser = userAgent.indexOf('mqqbrowser')
const iosBrowser = userAgent.indexOf('qbwebview')
const netType = userAgent.indexOf('netType') > -1 || userAgent.indexOf('NetType') > -1
return netType && (androidBrowser > -1 || iosBrowser > -1)
}
- 安卓與ios垦写。ios需要識別Safari和其他瀏覽器吕世。
// 判斷當(dāng)前設(shè)備是ios還是安卓
export const isAndroidOrIOS = () => {
const u = navigator.userAgent
const isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1 // android終端
const isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/) // ios終端
if (isAndroid) {
return 'android'
}
if (isiOS) {
return 'ios'
}
return false
}
// 是否是Safari瀏覽器
export const isSafari = () => {
return /Safari/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent)
}
- 安裝與未安裝。如果本機(jī)安裝了App梯投,則直接跳轉(zhuǎn)命辖,若是未安裝則安卓跳轉(zhuǎn)去下載頁面,ios跳轉(zhuǎn)至App Store分蓖。
// 下載或打開app
export const openApp = async () => {
// 內(nèi)置瀏覽器內(nèi)
if (isWeixin() || isQQ() || isWeibo()) {
console.log( '請在瀏覽器上打開=====')
} else {
// android端
if (isAndroid) {
const url = 'PATH'
// 安卓app的scheme協(xié)議
window.location.href = 'SCHEME'
// 若是未下載尔艇,則跳轉(zhuǎn)至下載地址
setTimeout(function () {
const hidden = window.document.hidden || (window.document as any).mozHidden || (window.document as any).msHidden || (window.document as any).webkitHidden
if (typeof hidden === 'undefined' || !hidden) {
// 下載地址
window.location.href = url
}
}, 2500)
}
// ios端
if (isIOS) {
const url = ‘App store path’
if (isSafari()) {
window.location.href = url
} else {
// ios的scheme協(xié)議
window.location.href = 'SCHEME'
setTimeout(function () {
const hidden = window.document.hidden || (window.document as any).mozHidden || (window.document as any).msHidden || (window.document as any).webkitHidden
if (typeof hidden === 'undefined' || !hidden) {
// App store下載地址
window.location.href = url
}
}, 200)
}
}
}
}