【问题标题】:How do you execute Javascript in React-Native WebView?你如何在 React-Native WebView 中执行 Javascript?
【发布时间】:2020-06-05 03:29:33
【问题描述】:

我正在尝试在加载到 iOS 建议的 WebView 中执行 javascript。我试图让一个非常简单的示例工作,但它始终抛出未定义或 TypeError。

代码如下:

import React, { Component } from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';
import { WebView } from 'react-native-webview';

export default class App extends Component {

  constructor(props){
    super(props)
    this.onPressButton = this.onPressButton.bind(this)
  }

  onPressButton(){
    this.webview.injectJavascript(`alert('hello')`)
  }

  render() {
    return (
      <View style={{ height: '100%' }}>
        <WebView
          ref={ref => (this.webview = ref)}
          javaScriptEnabled={true}
          source={{ uri: 'https://google.com' }}
        />
        <Button onPress={this.onPressButton} style={{ height: '10%' }} title="Test Javascript" />
      </View>

    );
  }
}

请不要推荐使用injectedJavascript,因为那不是我想要的功能。

也希望有任何其他方法。

【问题讨论】:

    标签: javascript ios reactjs react-native webview


    【解决方案1】:

    根据react-native-webview,你需要使用injectJavaScript,而不是injectJavascript。这将解决您的问题。

    另外,有一些事情需要改变

    1. 您无需绑定this.onPressButton = this.onPressButton.bind(this),而是可以使用箭头函数。
    2. 您不需要使用javaScriptEnabled={true}。它已经使用默认值true
    3. 在您的脚本包含true 之后。这是必需的,否则您有时会遇到静默失败。

    查看完整的示例代码

    import React, { Component } from "react";
    import { View, Button } from "react-native";
    import { WebView } from "react-native-webview";
    
    const script = `
        alert('hello')
        true;
        `;
    
    export default class App extends Component {
    
      onPressButton = () => {
        this.webview.injectJavaScript(script);
      };
    
      render() {
        return (
          <View style={{ flex: 1 }}>
            <WebView
              ref={ref => (this.webview = ref)}
              source={{ uri: "https://google.com" }}
            />
            <Button onPress={this.onPressButton} title="Test Javascript" />
          </View>
        );
      }
    }
    

    希望这对您有所帮助。如有疑问,请随意。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-05
      • 2017-05-06
      • 1970-01-01
      • 2019-05-02
      • 1970-01-01
      • 2019-05-14
      • 1970-01-01
      相关资源
      最近更新 更多