React Native WebView 内点击事件获取

问题描述:

  • 在RN的WebView里边,很多时候需要获取一个点击事件,来操作原生代码处理一些事情。可以使用onNavigationStateChange、onMessage来解决

代码

通过onNavigationStateChange :官方文档是这么写的Function that is invoked when the WebView loading starts or ends.那么这个方法到底是做什么的呢?

<WebView
    onNavigationStateChange={(event)=>{console.log(event)}}
    style={{flex:1}}
    source={{html:this.state.Html}}
/>
console log:这个输出是刚进入webview这个页面的输出 

{ target: 809,
  canGoBack: false,
  loading: false,
  title: '',
  canGoForward: false,
  navigationType: 'other',
  url: 'about:blank' }

当点击webview中的一个跳转按钮会输出如下:

{ target: 809,
  canGoBack: false,
  loading: false,
  title: 'tab2',
  canGoForward: false,
  navigationType: 'click',
  url: 'a.html' }      //这个a.html就是我们刚才点击的链接要访问的地址

其中不难发现,我们刚进入webview的时候 navigationType 为other,而点击跳转的时候则为click,好吧说到这里,估计大家都应该明白这个方法是做什么了。注意:这个方法无法阻止页面的跳转行为,所以大家只能通过这个方法获取用户的一些行为。从而做出判断。

但有很多情况,我们都是想,获取到这个行为,传值到RN再做其他事情,下面就做一个简单的例子onMessage。官方文档是这样描述的:

A function that is invoked when the webview calls window.postMessage. Setting this property will inject a postMessage global into your webview, but will still call pre-existing values of postMessage.

window.postMessage accepts one argument, data, which will be available on the event object, event.nativeEvent.data. data must be a string.

可以看出,这个方法用来和RN进行交互,必须注意的就是 当webview显示的页面中有 postMessage的同名函数时将会报错。

onMessage(func)

/*RN中*/
<WebView
   onNavigationStateChange={(event)=>{console.log(event)}}
   onMessage={(event)=>{console.log(event.nativeEvent)}}
   style={{flex:1}}
   source={{html:this.state.Html}}
/> 

/*html中*/
<a href='javascript:postMsg()'>

/*html中javascript,webview显示的html中一个a标签,调用postMsg,通过window.postMessage 传递123这个字符串到RN中。*/
<script>function postMsg(){window.postMessage('123')}</script>

console log:当点击a标签的时候后台会出现如下输出
/*onNavigationStateChange log */
 { target: 808,  
  canGoBack: false,
  loading: false,
  title: 'tab2',
  canGoForward: false,
  navigationType: 'other',
  url: 'react-js-navigation://postMessage?123' }
/* onMessage log*/
 { target: 808,
  canGoBack: false,
  data: '123',
  loading: false,
  title: 'tab2',
  canGoForward: false,
  url: 'about:blank' }

估计大家看到这里 应该脑洞大开了,这样在RN中就能够获取 标签、用户行为、交互数据。

Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐