Manu Gupta
Manu Gupta

Reputation: 351

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:

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>
    );
  }

}

Upvotes: 14

Views: 14526

Answers (3)

R&#233;my Ntshaykolo
R&#233;my Ntshaykolo

Reputation: 619

I ended up pasting the js source code around <script> my js code ... <script/> tags

Upvotes: 0

laurent
laurent

Reputation: 90863

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.

Upvotes: 8

martinarroyo
martinarroyo

Reputation: 9701

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

Upvotes: 4

Related Questions