Jake Chambers
Jake Chambers

Reputation: 563

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. 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.

Would appreciate any other approaches as well.

Upvotes: 1

Views: 2997

Answers (1)

SDushan
SDushan

Reputation: 4641

According to react-native-webview, you need to use injectJavaScript, not 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.
  2. You don't need to use javaScriptEnabled={true}. It is already using default value as true.
  3. After your script includes 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.

Upvotes: 2

Related Questions