首页 > 解决方案 > 你如何在 React-Native WebView 中执行 Javascript?

问题描述

我正在尝试在 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>

    );
  }
}

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

也将不胜感激任何其他方法。

标签: javascriptiosreactjsreact-nativewebview

解决方案


根据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>
    );
  }
}

希望这对您有所帮助。随意怀疑。


推荐阅读