uni-app和web-view頁面相互傳參方法實例
首先:這里說的是uni-app開發(fā)的APP項目,嵌入web-view頁面,并進行相互傳參,如果和您想了解的內容相符,請繼續(xù)閱讀。
一、說到web-view嵌入uni-app開發(fā)的APP,傳參方面很多人首先會想到url傳參。
<!-- app端 -->
<view>
<web-view src="www.xxxxx?name=張三"></web-view>
</view>//web端 alert(this.$route.query.name) //張三
這種方法是app向webview傳參最簡單的方式,但也存在許多弊端:
1.參數(shù)會被抓取,如果攜帶敏感信息會存在安全隱患;
2.url會有長度限制,如果攜帶的數(shù)據(jù)過多會傳不過去;
3.沒有對應的webview向app傳參的回傳方法;
4.(重要)不夠裝逼?。。?/p>
二、下面詳細說一下我在項目中用的方法,使用plus.webview.create(url, id, style, {data:{}})的方法攜帶參數(shù),并使用uni.postMessage()的方法回傳參數(shù)。
當app給web傳參時:
app中代碼如下:
let wv = plus.webview.create(
'xxx.xxxx.xxx?t=' + new Date().getTime(),//date保證不走緩存
'batch_view',
{
top: '0',
left: '0',
height: '100%',
width: '100%'
},
{
data: {
token: token,
userInfo: userInfo,
implantType: 'uniapp'
}
}) //不用data鍵值對的方式傳的話,h5接收后會是多個字段,而非一個對象
let currentWebview = this.$mp.page.$getAppWebview()
currentWebview.append(wv);//重要,否則會失效H5中代碼如下:
if (window.plus) {
plusReady();
}//加上此判斷以免再瀏覽器打開h5頁面時報plus is not define
function plusReady() {
if (plus.webview.getWebviewById("batch_view")) {
const appData = plus.webview.getWebviewById("batch_view").data;
alert(JSON.stringfy(appData))
}
}當web給app傳參時:
H5中代碼如下:
<!-- index.html中body引入uni.webview -->
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
<script
type="text/javascript"
src="https://unpkg.com/@dcloudio/uni-webview-js@0.0.3/index.js"
></script>
<!-- 以下為驗證是否引入成功(可刪) -->
<script type="text/javascript">
// 待觸發(fā) `UniAppJSBridgeReady` 事件后,即可調用 uni 的 API。
document.addEventListener("UniAppJSBridgeReady", function () {
uni.postMessage({
data: {
action: "6666", // 這是傳的參數(shù)
},
});
});
</script>
</body>//正常使用直接調用即可
uni.postMessage({
data: {
action: "noToken", // 這是傳的參數(shù)
},
});app中代碼如下:
//建議寫在該webview嵌入頁面的onLoad生命周期中
plus.globalEvent.addEventListener('plusMessage', function(msg) {
console.log(msg.data.args.data.arg)//web傳來的參數(shù)
if (msg.data.args.data.arg?.action == 'noToken') {
uni.clearStorageSync()
uni.reLaunch({
url: '/pages/login/index'
})
}
})這里說一下,官方官方推薦寫法是下面這樣,如果是自己再html中方創(chuàng)建的可以使用這種方式,我們是使用plus.webview.create創(chuàng)建的webview木有@message,故用了以上方法。
<web-view @message="handlePostMessage"></web-view>
總結
到此這篇關于uni-app和web-view頁面相互傳參的文章就介紹到這了,更多相關uni-app和web-view頁面相互傳參內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
基于prototype擴展的JavaScript常用函數(shù)庫
基于prototype擴展的JavaScript常用函數(shù)庫實現(xiàn)代碼,學習js的朋友可以參考下。2010-11-11
Bootstrap柵格系統(tǒng)使用方法及頁面調整變形的解決方法
這篇文章主要介紹了Bootstrap柵格系統(tǒng)使用方法及頁面調整變形的解決方法,需要的朋友可以參考下2017-03-03
Bootstrap在線電子商務網(wǎng)站實戰(zhàn)項目5
這篇文章主要為大家分享了Bootstrap在線電子商務網(wǎng)站實戰(zhàn)項目,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-10-10

