uniapp app端跳转第三方授权,外部html与app进行通信

使用uniapp 开发app时,可能会遇见需要获取第三方授权,使用第三方数据的情况,比如获取淘宝登录授权,人脸识别认证等,就需要通过webview跳转第三方页面,完成操作后又需要返回我们的程序内;对于前端来说,怎么监听用户是否操作完成是个问题;

//首先我们会通过接口来获取到后端返回的跳转第三方的数据链接,这里假设链接叫:data.url
//页面跳转url太长,跳转url获取不完整怎么办?
let url = encodeURIComponent(JSON.stringify(data.url))  //将文本字符串编码为一个有效的统一资源标识符
        uni.navigateTo({
			url: `/pages/home/tbAuthorization/tbAuthorization?url=${url}` //这里跳转的页面是放webview的页面
			})
//tbAuthorization webview页面
<template>
	<view>
		<web-view :src="url" @message="message"></web-view>
	</view>
</template>
<script>
	export default {
		data() {
			return {
				url: '',
			}
		},
		onLoad(opt) {
			this.url = JSON.parse(decodeURIComponent(opt.url)); //解码URI 组件。
		},
		methods: {
    //这个函数接收html返回的数据,我们根据返回的值执行相应的操作(ps: 返回的数据会存在event.detail.data的一个数组内)
			message(event) {
				console.log(event,"*********",event.detail.data)
				if (event.detail.data[0].action == 'success') {
					uni.reLaunch({
					 url:'/pages/home/selfSupport?type=tb'
					})
				}
			},
		}
	}
</script>
<!--html页面,这个页面是给后端的,他那边查询到结果后会自动跳转到这个html页面,通过这个与app内部进行通信-->

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>淘宝宝授权</title>
</head>
<body>
<img style="width: 72px;height: 72px;" src="assets/taobao.png" >
<p style="color: #1B1B1B;">淘宝已授权登录成功</p>
<button class="btn" type="button" onclick="test()">立即开启购物之旅</button>
</body>
<!--这个js一定要引入,是把uni嵌入html的,这样才能调用uni的方法(ps: 官网的链接地址是错误的,用这个)-->
<script type="text/javascript" src="https://js.cdn.aliyun.dcloud.net.cn/dev/uni-app/uni.webview.1.5.2.js"></script>
<script type="text/javascript">
    function test(){
        var timer = setInterval(function(){
//判断uni是否已经加载完成,不然在这之前调用是无效的
            if(window.uni){ 
                clearInterval(timer);
                uni.postMessage({ data: { action: 'success' } }),
                    uni.navigateBack()
            }
        },10)
       
    }
</script>
<style type="text/css">
    .btn{
        width: 50%;
        height: 45px;
        background: linear-gradient(90deg, #f6ad49, #ee7800);
        border-radius: 45px;
        border: 0;
        color: #fff;
        font-size: 16px;
        margin-top: 40%;
    }
    html{
        height: 100%;
    }
    body{
        height: 100%;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
    }
</style>
</html>

总结: 这个不难,但是我第一次做时很懵,所以记录一下,有一个问题还不明白,webview 有两个监听事件@message (网页向应用 postMessage 时,会在特定时机(后退、组件销毁、分享)触发并收到消息。)
@onPostMessage(网页向应用实时 postMessage)按理说第二个事件也能够接收到返回的消息数据,但是我做的时候怎么都获取不到,困扰了很久,还是不明白原因

  • 9
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值