如何在React Native中获取WebView内部?

时间:2019-08-05 20:14:40

标签: react-native webview fetch

我在React Native应用程序中有一个Webview。如何使用JavaScript在Web视图内执行请求(提取,Ajax或其他请求)?

这是我的网络视图中的代码

<!DOCTYPE HTML>
<html>
  <body>
    <p id="demo"></p>
    <script>
      var init = { method: 'POST' };
      fetch(url, init)
        .then(function (response) {
          return response.blob();
        })
        .then(function (myBlob) {
          document.getElementById("demo").innerHTML = myBlob
        });
    </script>
    <p></p>
  </body>
</html>

1 个答案:

答案 0 :(得分:0)

我建议将js代码注入WebView:

<WebView
    ref={(ref) => { this.webview = ref; }}
    source={{ uri: this.state.webViewUrl }}
    originWhitelist={['*']}
    javaScriptEnabledAndroid={true}
    injectedJavaScript={jsCode}
    onMessage={this._onMessage} // only if you want connection back
/>

并且您可以传递js代码-您可以将触发器放置在任意位置,例如,当button单击时,我调用该动作:

const jsCode = `
    document.querySelector('button').addEventListener("click", function() {  
        alert('Hello Web')
    }); 
    true;
    `