uniapp與webview之間的相互傳值


1.uni-app 如何發送數據到 H5? 其實很接單、在 web-view 中只需要通過 URL 就可以向 H5 進行傳參 例如在 uni-app 中:

<template>
	<view class="advertisement" style="width: 100%;">
		<web-view :src="url" @message="message"></web-view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			url:'/hybrid/html/local.html?data='
		};
	},
	onLoad(data) {
          //這里對要傳入到webview中的參數進行encodeURIComponent編碼否則中文亂碼 this.url+=encodeURIComponent(data.data) }, mounted() {}, methods: { message(event){ console.log(event.detail.data); } } }; </script> <style scoped="scoped" lang="scss"> @import './advertisement.scss'; </style>

  那么在 H5 中是如何接收值得呢?

console.log(getQuery('data'));  //獲取 uni-app 傳來的值
            
            
            //取url中的參數值
            function getQuery(name) {
                // 正則:[找尋'&' + 'url參數名字' = '值' + '&']('&'可以不存在)
                let reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
                let r = window.location.search.substr(1).match(reg);
                console.log(r);
                if(r != null) {
                    // 對參數值進行解碼
                    return decodeURIComponent(r[2]);
                }
                return null;
            }

2.webview向uniapp傳值

<script>
    document.addEventListener('UniAppJSBridgeReady', function() {
        //向uniapp傳值
        uni.postMessage({
            data: {
                action: 'message'
            }
        });
        uni.getEnv(function(res) {
            console.log('當前環境:' + JSON.stringify(res));
        });
    });
</script>    

uniapp接受

//message接受方法

<template>
    <view class="advertisement" style="width: 100%;">
        <web-view :src="url" @message="message"></web-view>
    </view>
</template>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM