zp26
zp26

Reputation: 1527

React Native WebView with local javascript

I'm going to create a React Native app with WebView. This View must contain local HTML and Javascript files. This is the code.

---> WVView.js

...
    render(){
        return (
            <View style={{flex:1}}>
                <StatusBar/>
                <WebView
                    nativeConfig={{props: {webContentsDebuggingEnabled: true}}}
                    ref={webview => { this.myWebView = webview; }}
                    source={require('./Resources/index.html')}
                    javaScriptEnabled={true}
                    injectedJavaScript={} 
                    onMessage={this.onWebViewMessage}
                    style={{flexBasis: 1, flexGrow:1}}
                    scrollEnabled={false}
                    />
            </View>
        );
    }
...

---> index.html

<div class="widget-container">
    <div id="test12"></div>
    <script type="text/javascript" src="./Utils.js"></script> 
    <script type="text/javascript" src="./WebViewBrdge.js"></script>   
    <script type="text/javascript" src="./TVS.js"></script>
</div>

---> Directory

|__ WVView.js
|__ Resources
       |__ index.html
       |__ Utils.js
       |__ WebViewBridge.js
       |__ TVS.js

Please, can you suggest the best way to develop this solution? When I read the documentation, I find code like source{{html:...}} or injectedJavascript for loading static local javascript. I don't find a similar example.

Now I can't load javascript files. Thanks

Upvotes: 4

Views: 11393

Answers (1)

Ankit Makwana
Ankit Makwana

Reputation: 2451

First of all add your files(Resources folder itself) in android assets directory in case of android and in XCode project in case of ios.
android: "YourApp/android/app/src/main/assets"
ios: "YourApp/ios"

Then take path of that folder in variable and set it as baseUrl.
android: "file:///android_asset/Resources"
ios: "Resources/"

You can use native file path to load html file

htmlPath = "file:///android_asset/Resources/index.html"; //file path from native directory;
<WebView
    source={{ uri: htmlPath, baseUrl: baseUrl }}
/>

After this your script will get loaded in webview.
Here is the link for your reference: https://github.com/react-native-community/react-native-webview/blob/master/docs/Guide.md#loading-local-html-files

Upvotes: 10

Related Questions