简介

app内嵌h5遇到的小问题记录,经验值+1

1.调app原生给的方法会有些不常用的写法

1
2
3
4
5
6
if (!isIOS) {
// 例如这句语法,如果用了eslint,rules里有"no-undef"这些会导致eslint报错,可以把这些规则关掉
javascript: nativeRegisteredTools.invoke("reg03", st);
} else {
window.webkit.messageHandlers.setShare.postMessage(st);
}

2.app原生给的方法有的是用location.href调用,不方便拦截,当需要拦截/捕获结果时,想到的办法就是用定时器

1
2
3
4
5
6
7
8
9
10
11
// 未登录(或者说是未获取)
window.location.href = `${encodeURI("cmgyt://yt.getuserinfo?callBackFun=ytGetuserinfo")}`
let timer = null
timer = setInterval(() => {
if(store.state.user.appUserId) {
// 登录完了
clearInterval(timer)
timer = null
next({ ...to, replace: true })
}
}, 50);

3.关于分享出去的h5唤起app的问题

h5并不能获取到设备是否安装了app及打开app,通常做法都是‘曲线救国’,判断页面是否隐藏(进入后台)来判断是否调起app(调起的方法由app提供)

在安卓中用scheme方法(非微信浏览器,微信浏览器中无法调起外部app,只能直接写跳转应用宝的链接window.location=”应用宝链接”),先调用window.location = this.scheme(app提供的调起app的scheme),再调用checkOpen()方法即可,checkOpen中判断页面是否隐藏来判断是否调起成功,其中3秒的延迟可能有问题(成功调起app后仍然弹出下载,未细究)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/**
* 获取页面隐藏属性的前缀
* 如果页面支持 hidden 属性,返回 '' 就行
* 如果不支持,各个浏览器对 hidden 属性,有自己的实现,不同浏览器不同前缀,遍历看支持哪个
*/
getPagePropertyPrefix() {
const prefixes = ["webkit", "moz", "ms", "o"];
let correctPrefix;
if ("hidden" in document) return "";
prefixes.forEach(prefix => {
if (`${prefix}Hidden` in document) {
correctPrefix = prefix;
}
});
return correctPrefix || false;
},
/**
* 判断页面是否隐藏(进入后台)
*/
isPageHidden() {
const prefix = this.getPagePropertyPrefix();
if (prefix === false) return false;
const hiddenProperty = prefix ? `${prefix}Hidden` : "hidden";
return document[hiddenProperty];
},
/**
* 获取判断页面 显示|隐藏 状态改变的属性
*/
getVisibilityChangeProperty() {
const prefix = this.getPagePropertyPrefix();
if (prefix === false) return false;
return `${prefix}visibilitychange`;
},
/**
* 检测是否唤端成功
*/
checkOpen() {
const visibilityChangeProperty = this.getVisibilityChangeProperty();
this.timer = setTimeout(() => {
const hidden = this.isPageHidden();
if (!hidden) {
// 端口唤起失败,弹出下载,下载apk
if(this.isAndroid) {
// 弹出下载,跳转到下载链接(app提供)
window.location = 'http://a.app.qq.com/o/simple.jsp?pkgname=***';
}
}
}, 3000);
if (visibilityChangeProperty) {
document.addEventListener(visibilityChangeProperty, res => {
clearTimeout(this.timer);
this.timer = null
});
return;
}
window.addEventListener("pagehide", () => {
clearTimeout(this.timer);
this.timer = null
});
}

在ios中,此app用的是moblink,https://www.mob.com/wiki/detailed?wiki=MobLink_for_Web&id=34

1
2
3
4
5
6
7
8
9
10
11
12
13
14
MobLink({
el: '#ytd',
path: '',
params: {
url: this.scheme
}
})
this.$dialog.confirm({
title: '',
message: '下载',
}).then(() => {
document.getElementById("ytd").click();
}).catch(() => {
});