uni-app和web-view页面相互传参

首先:这里说的是uni-app开发的APP项目,嵌入web-view页面,并进行相互传参,如果和您想了解的内容相符,请继续阅读。

一、说到web-view嵌入uni-app开发的APP,传参方面很多人首先会想到url传参。
<view><web-view src="www.xxxxx?name=张三"></web-view></view>
//web端alert(this.$route.query.name) //张三
这种方法是app向webview传参最简单的方式,但也存在许多弊端:

1.参数会被抓取,如果携带敏感信息会存在安全隐患;

2.url会有长度限制,如果携带的数据过多会传不过去;

3.没有对应的webview向app传参的回传方法;

4.(重要)不够装逼!!!

二、下面详细说一下我在项目中用的方法,使用plus.webview.create(url, id, style, {data:{}})的方法携带参数,并使用uni.postMessage()的方法回传参数。

当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 definefunction plusReady() {if (plus.webview.getWebviewById("batch_view")) {const appData = plus.webview.getWebviewById("batch_view").data;alert(JSON.stringfy(appData))}}

当web给app传参时:

H5中代码如下:

<body><div id="app"></div><script type="module" src="/src/main.ts"></script><scripttype="text/javascript"src="https://unpkg.com/@dcloudio/uni-webview-js@0.0.3/index.js"></script><script type="text/javascript">//待触发 `UniAppJSBridgeReady` 事件后,即可调用 uni 的 API。document.addEventListener("UniAppJSBridgeReady", function () {uni.postMessage({data: {action: "6666", // 这是传的参数},});});</script></body>
//正常使用直接调用即可uni.postMessage({data: {action: "noToken", // 这是传的参数},});

app中代码如下:

//建议写在该webview嵌入页面的onLoad生命周期中plus.globalEvent.addEventListener('plusMessage', function(msg) {console.log(msg.data.args.data.arg)//web传来的参数if (msg.data.args.data.arg?.action == 'noToken') {uni.clearStorageSync()uni.reLaunch({url: '/pages/login/index'})} })

这里说一下,官方官方推荐写法是下面这样,如果是自己再html中方创建的可以使用这种方式,我们是使用plus.webview.create创建的webview木有@message,故用了以上方法。

<web-view@message="handlePostMessage"></web-view>
ok,到这里就结束了,有不懂的小伙伴欢迎评论区提问。