mpx
mpx copied to clipboard
请问Webview API中的invoke该如何使用
我根据官网文档想使用invoke来实现H5和webview的通信。文档链接 发现没有反应,请问是哪里出问题了。是应为版本不对吗? 我的代码
//mpx
<template>
<view class="container">
<view wx:if="{{loading}}" class="loading">
<view class="loading-icon"></view>
<text class="loading-text">加载中...</text>
</view>
<web-view wx:else src="{{url}}" ></web-view>
</view>
</template>
<script lang="ts">
import { createPage } from '@mpxjs/core'
import mpx from '@mpxjs/core'
mpx.config.webviewConfig = {
apiImplementations: {
getTime: (options = {}) => {
console.log(111111);
const { params = {} } = options
console.log(params);
return {
text: params.text,
time: '2024-12-24'
}
}
}
}
createPage({
data: {
url: '',
loading: true
},
onLoad(options: any) {
this.setData({
url: 'http://localhost:5174/test/#/',
loading: false
})
}
})
</script>
//依赖版本
"@mpxjs/api-proxy": "^2.9.0",
"@mpxjs/core": "^2.9.0",
"@mpxjs/fetch": "^2.9.0",
"@mpxjs/pinia": "^2.9.0",
"@mpxjs/store": "^2.9.0",
"@mpxjs/utils": "^2.9.0",
//H5
<template>
<view class="container">
<view class="action-area">
<uv-button
size="large"
type="primary"
shape="circle"
:customTextStyle="buttonTextStyle"
@click="handleAction(handleStart)"
text="测试"
class="connect-btn"
></uv-button>
</view>
</view>
</template>
<script setup>
import { ref, onMounted } from "vue";
import { onLoad } from '@dcloudio/uni-app';
import webviewBridge from '@mpxjs/webview-bridge'
console.log(1111111);
// 按钮文本样式
const buttonTextStyle = ref({
'font-size': '35rpx'
});
const handleStart = () => {
webviewBridge.invoke('getTime', {
params: {
text: '我是入参'
},
success: () => {
webviewBridge.navigateTo({
url: './pages/index',
success: () => {
console.log('跳转成功')
}
})
// console.log('接收到的消息:', res.time)
},
fail:()=>{
webviewBridge.navigateTo({
url: './pages/index',
success: () => {
console.log('跳转成功')
}
})
}
})
}
// 统一处理按钮点击事件
const handleAction = async (action) => {
action();
};
</script>
//依赖版本:
"@mpxjs/webview-bridge": "^2.10.6",
宿主环境的版本太低,虽然没有贴对应的@mpxjs/webpack-plugin但是看其他版本应该也是在2.9.0,mpx是在2.9.70的版本开始支持invoke能力的,宿主环境的mpx版本统一升级后再试一下,功能应该是正常的
我升级到了2.10.6。发现还是没有用。而且我在H5调用的时候
webviewBridge.postMessage({
test:11111
})
webviewBridge.redirectTo({
url: 'pages/index',
success: () => {
console.log('跳转成功')
}
})
微信小程序的控制台返回的是: invokeAppService postMessage {} 37 invokeAppService redirectTo {url: "pages/index"} 37 也并没有跳转页面
如果是应用在小程序内的话,是不提供这个invoke得能力的,文档上写明了是RN环境下提供的,输出web的通信也可以使用invoke,另外贴的例子 webviewBridge.postMessage({ data: { test:11111 } })是正确的传递规范, redirectTo这个,我不知道你这面宿主环境的文件结构,没办法给出准确的原因推断,方便的话,可以提供一个最简复现demo给到我