React Native-WebView-加载js文件

时间:2019-04-02 09:29:48

标签: react-native webview react-native-android react-native-ios

我需要动态加载JS(取决于用户的首选项,因此无法在index.html中进行全部硬编码),但是我的应用程序存在问题。

方案1就像一个吊饰:

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>

应用

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

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

但是当我尝试通过html在源代码中进行操作时,我缺少了JS库。

方案2-无法正常工作

应用

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

我想避免使用外部库加载js文件。

1 个答案:

答案 0 :(得分:0)

首先根据您的情况加载index.html文件。 然后引用一个webview组件。在webview加载index.html文件之后,我们可以注入javascript来加载js文件,如下所示:

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

无论何时要加载js文件,都可以调用此函数。但是,请确保webview已加载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);
}

注意:仅在android上检查。

相关问题