uniapp与webview通讯 在uniapp中使用webview时,可以通过postMessage和addEventListener实现两者之间的通讯。以下是一个简单的示例: 在uniapp中: <web-view ref="webviewRef" :src="u2" @message="backmsg"></web-view> <script> sendmsg(params) {//发送信息到webview页面 const self = this; self.currentWebview = self.$scope.$getAppWebview().children()[0]; self.currentWebview.evalJS(`${"msgFromApp"}(${JSON.stringify(params)})`);//传递大量数据 }, backmsg(event) { // 网页回调,收到webview发来的消息 console.log('webview:', event) } </script> 在HTML中(webview中的页面): <!DOCTYPE html> <html> <head> <title>WebView Page</title> <script src='/js/uni.webview.1.5.5.js'></script> </head> <body> <h1>WebView Page</h1> <script> var plus,sbid=''; document.addEventListener('plusready', function(){// 页面加载时执行初始化plus var mainActivity = plus.android.runtimeMainActivity(); var Settings= plus.android.importClass("android.provider.Settings"); sbid=Settings.Secure.getString(mainActivity.getContentResolver(),Settings.Secure.ANDROID_ID);//得到设备ID }, false ); document.addEventListener('UniAppJSBridgeReady', function(){ //开启uniapp句柄监听消息 uni.getEnv(function(res) { //alert('当前环境:' + JSON.stringify(res)); window["msgFromApp"] = (data) => { let a = JSON.parse(JSON.stringify(data)); console.log("app: ", JSON.stringify(a)+" url:"+location.href); if(a.key=='back'){ console.log("收到后退命令:",location.href.indexOf('mod=index&mobile=2')>=0); if(location.href.indexOf('mod=index&mobile=2')>=0){//当前为首页时发送退出通知 uni.postMessage({ data: {action: "exit"} }); console.log("发送exit通知"); }//else{history.go(-1);} } }; }); }); function gominifun(){//向uniapp发送消息,跳转小程序 uni.postMessage({data:{action:'mini',gid:'gh_8c49cee9e15d',path:'pages/index/index'}}); } </script> </body> </html> 在这个例子中,uniapp通过postMessage向webview发送了一个消息对象,webview页面通过监听message事件来接收这个消息。这样uniapp和webview之间就可以通过postMessage进行通信了。 |
![]() |
上一篇: | uniapp中跳转微信小程序 |
下一篇: | JS之location对象详解 |