Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include external JavaScript file in the WebView of React Native App

I'm trying to include an external JavaScript file inside a WebView of my React Native project. The file I wish to include is a third party library not available on npm written in plain JavaScript (No ES5 or higher). I need a solution for injecting my JS file in the WebView of the React Native project without importing it or making it an npm module.

I have tried the following methods but nothing works as for now:

  • I have tried to load the script like this: Insert script tag
  • I have tried to load the script dynamically in injectedJavaScript following the answer here: Link JS file from a JS file

This is my external AppGeneral.js:

function AppGeneral(){
     alert("Ok");
}
var app = new AppGeneral();

This is my index.ios.js file:

export default class sampleReactApp extends Component {
  render() {

    let HTML = `
    <html>
      <head>
        <script type="text/javascript" src="js/AppGeneral.js"></script>
      </head>
      <body>
        <div id="workbookControl"></div>
            <div id="tableeditor">editor goes here</div>
            <div id="msg" onclick="this.innerHTML='&nbsp;';"></div>
      </body>
    </html>
    `;

     let jsCode = `
     alert("Js");
    `;
    return (
        <View style={styles.container}>
            <WebView
                style={styles.webView}
                ref="myWebView"
                source={{ html: HTML }}
                injectedJavaScript={jsCode}
                javaScriptEnabledAndroid={true}
            >
            </WebView>
        </View>
    );
  }

}
like image 374
Manu Gupta Avatar asked Nov 23 '16 10:11

Manu Gupta


2 Answers

The only way to load JavaScript in a RN WebView is using the injectedJavaScript property, and this can only take a plain string (not a file path). In my case, I've done it this way:

First generate a file that contains your JS file converted to a plain string:

const fs = require('fs-extra');
const filePath = '/path/to/your/lib.js';
const js = await fs.readFile(filePath, 'utf-8');
const json = 'module.exports = ' + JSON.stringify(js) + ';';
await fs.writeFile('/my-rn-app/external-lib.js', json);

And make sure "/my-rn-app/external-lib.js" is somewhere where it can be imported in React Native.

Then simply import the file and inject it in the WebView:

const myJsLib = require('external-lib.js');
const webView = <WebView injectedJavaScript={myJsLib} .....

This is not a particularly pretty solution but it works well.

like image 84
laurent Avatar answered Oct 21 '22 09:10

laurent


Maybe you can try bundling your JS file as an asset and then refer to the file as you would in a 'native' WebView. Have a look at this answer for Android and this ones for iOS, [1] and [2].

like image 44
martinarroyo Avatar answered Oct 21 '22 08:10

martinarroyo