WebView JS與RN進行通訊

來源:互聯網
上載者:User

標籤:tle   eve   enter   val   button   方便   asc   sheet   doc   

RN0.37終於官方增加了WebView與React Native的通訊,之前一真使用的是第三方控制項React-Native-WebView-Bridge,但不是知道怎麼回事這個第三方控制項喊了很長時間最終卻是另一作者提交了該功能的官方版本。言歸正轉,由於Web的需求豐富多樣所以如果不能實現WebView裡的JS與RN的通訊的話,就顯得特別不方便,下面程式碼範例如何擷取當前的WebView Title,(即時Title,第一次載入的標題RN有Nativestate的方式擷取,但如果Title被動態變更的話通過該辦法就擷取不了)。

import React, { Component } from ‘react‘;import {  AppRegistry,  StyleSheet,  Text,  View,  WebView,  Button,} from ‘react-native‘;export default class RN37 extends Component {  webview = null;  //執行JS代碼,會被轉為字串,使用injectedJavaScript方法用eval執行字串方法  postMessage = () => {    if (this.webview) {      this.webview.postMessage(‘window.postMessage("Title:"+document.title);‘);    }  }  //接收WebView JS事件訊息  onMessage = e => {    alert(e.nativeEvent.data);  }  render() {    return (      <View style={styles.container}>        <Button enabled onPress={this.postMessage} title="Send Message to Web View" />        <WebView          ref={webview => { this.webview = webview; } }          style={{            flex: 1,            width:360,          }}          injectedJavaScript="document.addEventListener(‘message‘, function(e) {eval(e.data);});"          source={{uri:"https://www.baidu.com"}}          onMessage={this.onMessage}          />      </View>    );  }}const styles = StyleSheet.create({  container: {    flex: 1,    justifyContent: ‘center‘,    alignItems: ‘center‘,    backgroundColor: ‘#F5FCFF‘,  }});AppRegistry.registerComponent(‘RN37‘, () => RN37);

執行效果

WebView JS與RN進行通訊

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.