简体   繁体   English

你如何在 React-Native WebView 中执行 Javascript?

[英]How do you execute Javascript in React-Native WebView?

I'm trying to execute javascript in a WebView that is loaded on an iOS advice.我正在尝试在加载到 iOS 建议上的 WebView 中执行 javascript。 I'm trying to get a painfully simple example to work but it is consistently throwing an undefined or TypeError.我试图让一个痛苦的简单示例工作,但它始终抛出未定义或类型错误。

Here is the code:这是代码:

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>

    );
  }
}

Please don't recommend to use injectedJavascript because that is not my desired functionality.请不要推荐使用injectedJavascript,因为这不是我想要的功能。

Would appreciate any other approaches as well.也将不胜感激任何其他方法。

According to react-native-webview , you need to use injectJavaScript , not injectJavascript .根据react-native-webview ,您需要使用injectJavaScript ,而不是injectJavascript That'll fix your issue.那会解决你的问题。

Also, there are few things that need to change此外,还有一些事情需要改变

  1. You don't need to bind this.onPressButton = this.onPressButton.bind(this) instead you can use an arrow function.您不需要绑定this.onPressButton = this.onPressButton.bind(this)而您可以使用箭头函数。
  2. You don't need to use javaScriptEnabled={true} .您不需要使用javaScriptEnabled={true} It is already using default value as true .它已经使用默认值作为true
  3. After your script includes true .在您的脚本包含true This is required, or you'll sometimes get silent failures.这是必需的,否则您有时会遇到无声的失败。

Check complete sample code检查完整的示例代码

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

Hope this helps you.希望这对你有帮助。 Feel free for doubts.如有疑问,请放心。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM