欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

网页视图中的 HTML 调用 uniapp 应用程序接口教程

最编程 2024-03-07 22:08:17
...

webview中的HTML调用uniapp的API教程

使用uni的api,需要引入

https://js.cdn.aliyun.dcloud.net.cn/dev/uni-app/uni.webview.0.1.52.js

引用依赖的文件

<!-- uni 的 SDK,必须引用。 --> 
<script type="text/javascript" src="//js.cdn.aliyun.dcloud.net.cn/dev/uni-app/uni.webview.0.1.52.js"></script>

在引用依赖的文件后,需要在 HTML 中监听 UniAppJSBridgeReady 事件触发后,才能安全调用 uni 的 API。

document.addEventListener('UniAppJSBridgeReady', function() {  
    uni.getEnv(function(res) {  
        console.log('当前环境:' + JSON.stringify(res));  
    });  
});

监听 web-view 的 message 事件

监听 web-view 组件的 message 事件,然后在事件回调的 event.detail.data 中接收传递过来的消息。

<template>  
    <view>  
        <web-view src="http://192.168.1.1:3000/test.html" @message="handleMessage"></web-view>  
    </view>  
</template>  

<script>  
    export default {  
        methods: {  
            handleMessage(evt) {  
                console.log('接收到的消息:' + JSON.stringify(evt.detail.data));  
            }  
        }  
    }  
</script>

从 HTML 向应用发送消息

uni.postMessage 中的参数格式,必须是 data: {}。也就是说,传递的消息信息必须在 data 这个对象中。

document.addEventListener('UniAppJSBridgeReady', function() {  
    uni.postMessage({  
        data: {  
            action: 'postMessage'  
        }  
    });  
});

每次执行 postMessage 后,传递的消息会以数组的形式存放。因此,在 web-view 的 message 事件回调中,接收到的 event.detail.data 的值是一个数组。