Sunday, January 20, 2019

Injecting Custom JavaScript Into React Native Webview

This tutorial explains how to inject custom javascript in webview component in react native application.The injectedJavaScript is a custom prop of the React native Webview component. You can pass any JavaScript code ( as string ) to this prop, and React native will inject this JavaScript code into the Webview. The injected JavaScript will get executed once the Webview is finished loading.
Injecting Custom JavaScript Into React Native Webview

React Native Injecting Custom JavaScript In WebView  Component :

Lets see the complete source code to inject javascript code in webview component in react native application.
/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from "react";
import { Platform, StyleSheet, View, WebView } from "react-native";

export default class App extends Component {

  render() {
    let html = `<div id="myContent"> This is skptricks blog </div>`;
    let jsCode = `document.querySelector('#myContent').style.backgroundColor = '#C2DFFF'; `;

    return (
      <View style={styles.container}>
        <WebView
          style={styles.webView}          
          html={html}
          injectedJavaScript={jsCode}
          javaScriptEnabledAndroid={true}
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
  },
  headerText: {
    fontSize: 20,
    textAlign: "center",
    margin: 10,
    fontWeight: "bold"
  },
});

Screenshot :

Injecting Custom JavaScript Into React Native Webview

This is all about Injecting Custom JavaScript Into React Native Webview. Thank you for reading this article, and if you have any problem, have a another better useful solution about this article, please write message in the comment section.

No comments:

Post a Comment