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:
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=' ';"></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>
    );
  }
}
                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.
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].
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With