官方有相应的通讯就不写了 写下自己在实际使用用到的操作
-
操作webview样式
onReady() { // #ifdef APP-PLUS var currentWebview = this.$scope.$getAppWebview() //此对象相当于html5plus里的plus.webview.currentWebview()。在uni-app里vue页面直接使用plus.webview.currentWebview()无效,非v3编译模式使用this.$mp.page.$getAppWebview() var wv= null; let status_bar = uni.getSystemInfoSync().statusBarHeight; setTimeout(function() { wv = currentWebview.children()[0] wv.setStyle({top:status_bar,height:(uni.getSystemInfoSync().windowHeight - status_bar) }) }, 1000); //如果是页面初始化调用时,需要延时一下 // #endif },
2. 实际使用
`// 1.本地内嵌
<script type="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: 'message'
}
});
uni.getEnv(function(res) {
console.log('当前环境:' + JSON.stringify(res));
});
});
</script>
// 2. plus.webview.create
// 3. subNvue
第一种和h5 iframe方式一致 第三方网页对postMessage()方式没有相应实现
然后src为第三方网址时可以通过uni注入plus对象进行通讯
// #ifdef APP-PLUS
var currentWebview = this.getAppWebview() //获取当前页面的webview对象
setTimeout(function() {
wv = currentWebview.children()[0]
let jsCode = (function(){ setTimeout(()=>{ if(window?.myApp?.transmit) return; window.myApp = { transmit: function(e){ console.log(e) //e的type为string let data = { options: { timestamp: +new Date() }, name: 'postMessage', arg: e } plus.webview.postMessageToUniNView( { type: "WEB_INVOKE_APPSERVICE", args: { data: data, webviewIds: [parent.id] } }, "__uniapp__service" ); } }; window.myApp.transmit({ data: 'hellow' }) },2000) })()
wv.evalJS(jsCode)
}, 1000); //如果是页面初始化调用时,需要延时一下
// #endif
页面内接收
<web-view :src="src" @message="handlePostMessage">
第二种 无法接收到h5发送的消息 注入evalJs也无法得到相应消息
第三种 通过evalJs将uniapp注入到weex环境
// 调用 webview 内部逻辑
evalJs: function() {
let jsCode = '(function(){ window.myApp = { transmit: function(e){ window._dcloud_weex.postMessage(e); } } })()';
this.$refs.webview.evalJs(jsCode);
}
这样可以接收到消息而且nvue页面必须为引号无法使用``