1

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.

0

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.