Taro小程序webview使用API及避坑指南

Taro小程序webview组件是一个可以用来承载网页的容器,会自动铺满整个小程序页面。
注意:个人类型的小程序暂不支持使用。客户端 6.7.2 版本开始,navigationStyle: custom 对 webview组件无效,小程序插件中不能使用。
以上意味着:webview的页面无法自定义导航栏,无法自定义高度、样式等,去加载了webview,那么webview中的h5页面将具备最高控制权,
所以小程序开发者如果想在webview组件上做任何修改,只能建议自定义组件。
小程序开发者可以做哪些?
1.可以自定义设置页面标题

最好写在生命周期constructor、willMount、didMount中,仅第一次生效;同时如果加载的h5页面配置了title标题,h5页面的title会覆盖页面级设置的标题。
自定义标题:

Taro.setNavigationBarTitle({
  title: '自定义标题'
});

2.方法说明,引入及API使用

参数 类型 必填 说明
src string webview 指向网页的链接。可打开关联的公众号的文章,其它网页需登录小程序管理后台配置业务域名。
onMessage BaseEventOrigFunction<onMessageEventDetail> 网页向小程序 postMessage 时,会在特定时机(小程序后退、组件销毁、分享)触发并收到消息。e.detail = { data }
onLoad BaseEventOrigFunction<onLoadEventDetail> 网页加载成功时候触发此事件
onError BaseEventOrigFunction<onErrorEventDetail> 网页加载失败的时候触发此事件

代码示例:

import Taro, { Component,getCurrentInstance } from '@tarojs/taro'
import { View, WebView } from '@tarojs/components'

export default class extends Component {
  config = {
    navigationBarTitleText: ''
  }

  url = ''
  title = ''

  componentWillMount() {
    //使用decodeURIComponent,是因为如果直接获取url,如果url中含有"?"等携带参数,
    //会导致参数丢失,所以传入url时使用encodeURIComponent做一次转义
    this.url = decodeURIComponent(getCurrentInstance()?.router?.params?.url || '')
    this.title = decodeURIComponent(getCurrentInstance()?.router?.params?.title || '')
    Taro.setNavigationBarTitle({ title: this.title })
  }

  //网页向小程序 postMessage 时,会在特定时机(小程序后退、组件销毁、分享)触发并收到消息
  onWebMessage(e){
    const {data} = e.detail;
    console.log("onWebMessage==",data)
  }

  //网页加载成功时候触发此事件
  onWebLoad(e){
    const {src} = e.detail;
    console.log("onWebLoad==",src)
  }

  //网页加载失败的时候触发此事件
  onWebError(e){
    const {errMsg,url} = e.detail;
    console.log("onWebError==",errMsg)
  }

  render () {
    return (
      <View className='webview'>
        <WebView src={this.url}
                 onMessage =  {this.onWebMessage}
                 onLoad=  {this.onWebLoad}
                 onError =  {this.onWebError}
        />
      </View>
    )
  }
}

同时h5页面如何调用原生api,如何向webview页面发送消息,可以参考我的另外一篇博客:Taro webview中的h5页面如何使用原生小程序API

以上即本人使用心得,如有帮助,记得点赞三连~谢谢~

客官且慢~扫一扫个人微信小程序,琳琅街比价,谢谢支持~

猜你喜欢

转载自blog.csdn.net/qq_33539839/article/details/120012729