Sebastian Bochan
Sebastian Bochan

Reputation: 37578

React native - webview - load js files

I need to load JS dynamically (depends on user preferences, so cannot hardcoded all in the index.html), but have the problem with that in my app.

Scenario 1 works like a charm:

index.html

<html>
  <head>
  </head>
  <body>
    <h1>Highcharts webview demo</h1>
    <div id="container" style="width:100%; height:500px;"></div>
    <script type="text/javascript" src="library.js"></script>
    <script>
      library works
    </script>
  </body>
</html>

app

const webapp2 = require('../web/index.html')

render() {
return <View>
      <WebView
        source={webapp2}
        originWhitelist={'["*"]'}
        javaScriptEnabled={true}
        domStorageEnabled={true}
        scalesPageToFit={true}
        scrollEnabled={false}
      />
</View>
}

But when I try to do it by html in source, I have the missing JS library.

Scenario 2 - not working

app

  render() {

    // Create container for the chart
    return <View style={styles.container}>
      <WebView
        source={{html:`<html><head><script type="text/javascript" src="library.js"></script></head><body><div id="container" style="width:100%; height:500px;"></div><script>Library does not exist yet</script></body></html>`, baseUrl: 'web/'}}
        originWhitelist={'["*"]'}
        javaScriptEnabled={true}
        domStorageEnabled={true}
        scalesPageToFit={true}
        scrollEnabled={false}
      />
    </View>
  }

I would like to avoid use external libraries to load js files.

Upvotes: 4

Views: 7720

Answers (1)

Ankit Makwana
Ankit Makwana

Reputation: 2451

First of load index.html file according to your scenario 1. Then take a ref of webview component. After webview loads the index.html file, we can inject javascript to load js file like below:

<WebView
    ref={ref => (this.webview = ref)}
    source={webapp2}
    originWhitelist={'["*"]'}
    javaScriptEnabled={true}
    domStorageEnabled={true}
    scalesPageToFit={true}
    scrollEnabled={false}
    onLoad={() => { this.injectJSFileFromWeb(); }}
/>

you can call this function whenever you want to load js file. but, make sure webview has loaded html.

injectJSFileFromWeb() {
    //give the filename according to your need
    var jsFileName = "library2.js";
    var fp = `
        var corescript = document.createElement('script');
        corescript.type = 'text/javascript';
        corescript.src = "${jsFileName}";
        var parent = document.getElementsByTagName('head').item(0);
        parent.appendChild(corescript);
        void(0);
    `;
    this.webview.injectJavaScript(fp);
}

Note: checked only on android.

Upvotes: 4

Related Questions