起因
現(xiàn)在市場上各種跨平臺開發(fā)方案百家爭鳴各有千秋,個人認為最成熟的還是hybird方案榆芦,簡單的說就是寫H5各種嵌入,當然作為前端工程師最希望的也就是公司采用hybird方案當作技術(shù)路線喘鸟。
所謂的hybird方案很多時候單獨指h5嵌入app頁面匆绣,本專輯講的卻比這個要廣泛很多,作者想寫一個基礎框架嵌入所有移動端app什黑,包括app殼子崎淳、微信公眾號、微信小程序愕把、支付寶頁面拣凹、支付寶小程序等,而且是一套代碼可以同時嵌入各種app恨豁,這樣最大程度上節(jié)約開發(fā)成本嚣镜,當然我們的框架也會注意到開發(fā)質(zhì)量,如前面文章提到的移動端頁面切換動畫也是為了提升用戶體驗橘蜜。
大hybird方案必須要處理的是判斷當前程序運行在什么環(huán)境中菊匿,故有此篇判斷瀏覽器類型的合集。
微信瀏覽器
微信公眾號或微信內(nèi)直接打開鏈接
var ua = navigator.userAgent.toLowerCase();
if (ua.match(/MicroMessenger/i) == "micromessenger") {
// 在微信中打開
}
微信小程序
// html 引入
<script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.3.2.js"></script>
// js中如下判斷
var ua = navigator.userAgent.toLowerCase();
if(ua.match(/MicroMessenger/i)=="micromessenger") {
wx.miniProgram.getEnv((res)=>{
if (res.miniprogram) {
// 在微信小程序中打開
}
})
}
支付瀏覽器
支付寶瀏覽器中
var ua = navigator.userAgent.toLowerCase();
if (ua.match(/Alipay/i)=="alipay") {
// 在支付寶中打開
}
支付寶小程序中
// html 引入
<script type="text/javascript" src="https://appx/web-view.min.js"></script>
// js中如下判斷
var ua = navigator.userAgent.toLowerCase();
if (ua.match(/Alipay/i)=="alipay") {
my.getEnv((res)=>{
if (res.miniprogram) {
// 在支付寶小程序中打開
}
})
}
app殼子
在app殼子中往往使用往ua里面添加唯一標識符來做標識计福。
var ua = navigator.userAgent.toLowerCase();
if (ua.match(/myapp/i)=="myapp") {
// 在自家app殼子里面
}
其他的沒有標識的app跌捆,最后的倔強
可以使用路徑上新增參數(shù)的方式去識別,當識別到參數(shù)就在session保存起來象颖,這樣作用周期就是某一次打開佩厚,防止了數(shù)據(jù)污染。
完整版js
我習慣命名browser-env.js
// 自家app殼子的ua標識
const SELF_APP_UA_KEY = 'myapp'
const browserEnv = {
enum: {
BROWSER: 0, // 瀏覽器訪問说订,
SELFAPP: 10, // 自己家app
WX: 20, // 微信瀏覽器
WX_MINIPROGRAM: 21, // 微信小程序
ALI: 30, // 支付寶瀏覽器
ALI_MINIPROGRAM: 31,// 支付寶小程序
// ... 更多擴展
},
webType: 0,
initWebType: function (type) {
// 設置值抄瓦,并且讓其不可改變,防止開發(fā)隨意篡改陶冷。
Object.defineProperty( this, "webType", {
value: type,
writable: false,
configurable: false
});
},
// 識別瀏覽器類型
identifyBrowser() {
// ua和枚舉的淺層映射放這里闺鲸,ua能匹配的都這么處理
let codeKey = {
'micromessenger': this.enum.WX,
'alipay': this.enum.ALI
}
// 添加自家app映射
codeKey[SELF_APP_UA_KEY] = this.enum.SELFAPP;
// 獲取ua
let ua = navigator.userAgent.toLowerCase();
let type = this.enum.BROWSER
for (let key in codeKey) {
let mk = `/${key}/i`;
let reg = eval(mk)
if (ua.match(reg) == key) {
type = codeKey[key]
break ;
}
}
// ua 匹配不出來的,繼續(xù)匹配 // 延遲引入JSSDK往后處理埃叭,不講究可以直接寫入html
if (type == this.enum.WX) {
wx.miniProgram.getEnv((res)=>{
if (res.miniprogram) {
type = this.enum.WX_MINIPROGRAM
}
})
} else if (type == this.enum.ALI) {
my.getEnv((res)=>{
if (res.miniprogram) {
type = this.enum.ALI_MINIPROGRAM
}
})
}
this.initWebType(type)
},
install(Vue) {
this.identifyBrowser()
Vue.config.globalProperties.$browserEnv = browserEnv;
},
}
export default browserEnv;
老規(guī)矩摸恍,全局引入
import browserEnv from '@/utils/browser-env.js'
app.use(browserEnv)
使用,個人覺得使用枚舉更加清晰吧,一頓寫數(shù)字其實也挺好
if (this.$browserEnv.webType == this.$browserEnv.enum.WX) {
// 在微信中
}
原創(chuàng)不易立镶,轉(zhuǎn)載請注明出處壁袄,歡迎留言提議。