uni-app嵌套webview监听事件

发布于:2024-04-08 ⋅ 阅读:(107) ⋅ 点赞:(0)

uniapp-主页面

<template>
  <view class="content">
    <image class="logo" src="@/static/logo.png"></image>
    <view class="text-area">
      <text class="title">Hello RuoYi</text>
	  <button @tap="navGen"> 跳转页面</button>
    </view>
  </view>
</template>

<script>
  export default {
	  data(){
		return{
			codeUrl:'1',
		}
	  },
    onLoad: function() {
    },
	methods:{
		navGen(){
			uni.navigateTo({
			      url: '/pages/webview/webview?url=' + encodeURIComponent('http://www.baidu.com')
			    });
		}
	}
  }
</script>

<style>
</style>

uni-app跳转页面

<template>
  <web-view :src="url" @message="onMessage"></web-view>
</template>

<script>
	// webview.vue
	export default {
	  onLoad(option) {
	    // 获取传递过来的URL参数
	    if (option.url) {
	      this.url = decodeURIComponent(option.url);
	    }
	  },
	  data() {
	    return {
	      url: ''
	    };
	  },
	  methods:{
		onMessage(e) {
			// 接收webview发送的消息
			console.log('收到消息',e);
			if (e.detail.data[0].action == 'success') {
				uni.reLaunch({
				 url:'/pages/report/index'
				})
			}
		}
	  }
	}
</script>

<style>
</style>

外部页面

引入因为vue页面无法使用uniapp事件

<script type="text/javascript" src="https://js.cdn.aliyun.dcloud.net.cn/dev/uni-app/uni.webview.1.5.2.js"></script>

具体页面

//判断uni是否已经加载完成,不然在这之前调用是无效的
            var timer = setInterval(function(){
                if(window.uni){ 
                    clearInterval(timer);
                    uni.postMessage({ data: { action: 'success' } });
                }
            },1000)