Desmond Chen
Desmond Chen

Reputation: 95

react-native-webview load a local HTML file but got plain text

I try to load a HTML file depends on someother .js file.

So I write code like this, but got plain text in webview.

render = () => {
    let source;
    if (__DEV__) {
      source = require('./vendor/Editor/index.html');
    } else {
      source =
        Platform.OS === 'ios'
          ? require('./vendor/Editor/index.html')
          : {uri: 'file:///android_asset/vendor/Editor/index.html'};
    }

    return (
      <WebView
        startInLoadingState
        source={source}
        onMessage={this.handleMessage}
        automaticallyAdjustContentInsets={false}
        style={[
          AppStyles.container,
          styles.container,
          {height: this.state.visibleHeight},
        ]}
      />
    );
  };

enter image description here

And I simplify the code like this, but it doesn't work too.

  render = () => {
    setTimeout(() => {
      this.webview.injectJavaScript(
        'window.ReactNativeWebView.postMessage(document.body.innerHTML)',
      );
    }, 3000);

    return (
      <WebView
        source={require('./vendor/GrEditor/index.html')}
        onMessage={e => console.log('e: ', e)}
      />
    );
  };

Sorry for poor grammar.

Upvotes: 8

Views: 8295

Answers (1)

Ankit Makwana
Ankit Makwana

Reputation: 2451

To load local html file in android you need to use android asset path even in dev mode. So it will be like this:

let source = Platform.OS === 'ios'
          ? require('./vendor/Editor/index.html')
          : {uri: 'file:///android_asset/vendor/Editor/index.html'};

Copy your vendor folder in assets folder(project_folder\android\app\src\main\assets) of android.
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