React-Native WebView postMessage获取json对象

时间:2017-09-20 13:32:28

标签: javascript jquery react-native webview

我可以成功将postMessage发送到WebView,但我的问题是如何从event.data中提取json对象。有没有办法获得json对象

document.addEventListener("message", function(event) {
  console.log("Received post message", event);//Get Event from React Native
  alert(event.data);
}, false);

以下是代码:

import React, { Component } from 'react'
import { ScrollView, Button, WebView, View, TouchableHighlight, Text } from 'react-native'
import { connect } from 'react-redux' 


class UserData extends Component {
  constructor (props) {
    super(props)
    this.state = {}
 }
render () {
  let html = `
  <!DOCTYPE html>
  <html lang="en">
  <head>
  <meta charset="utf-8">
  <script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js" charset="utf-8"></script>
  </head>
  <body>
  <div id="myContent">
  </div>
  </body>
  </html>  
` 

let jsCode = `
document.addEventListener("message", function(event) {
  console.log("Received post message", event);
  alert(event.data);
}, false);

var data = [150, 230, 180, 90, 151, 55];

var svg = d3.select("#myContent") //used to display graph
        .append("svg")
        .attr("width", 900)
        .attr("height", 2000);

svg.selectAll(".bar")
    .data(data)
    .enter()
    .append("rect")
    .attr({
        class : "bar",
        width : function(d) {return d;},
        height: "40",
        y : function(d, i) {return i*50 + 10;},
        x : "10"
    });

`

return (
    <View style={styles.container}>
      <TouchableHighlight 
      onPress={() => this.sendPostMessage()}>
          <Text>Send post message from react native</Text>
      </TouchableHighlight>
      <WebView
        style={styles.webView}
        ref={( webView ) => this.webView = webView}
        html={html}
        injectedJavaScript={jsCode}
        javaScriptEnabled={true}
        scrollEnabled={true}
      >
      </WebView>
    </View>
  );
  }//End of Render

  sendPostMessage() {
    console.log( "Sending post message" );
    var UserData={
      UserName: "XYZ",
      userid: "123456789"
    }
    this.webView.postMessage(UserData); //Post Message to WebView
  }//End of Send Post Message function

}//End of Class

有没有人知道如何从反应原生

接收的WebView中提取json-object

使用的文档:http://facebook.github.io/react-native/releases/0.46/docs/webview.html

我试过了

document.addEventListener("message", function(event) {
   console.log("Received post message", event);//Get Event from React Native
   alert(event.data);
   alert(event.data.UserName);
}, false);

1 个答案:

答案 0 :(得分:1)

认为你必须JSON.string(UserData)=&gt; window.postMessage(串) https://facebook.github.io/react-native/docs/webview.html#onmessage

  

window.postMessage接受一个参数data,它将在事件对象event.nativeEvent.data上可用。数据必须是一个字符串。