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

1

8

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.

Phenazine answered 7/4, 2020 at 2:56 Comment(0)
G
10

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

Gezira answered 28/4, 2020 at 6:11 Comment(1)
I see your doing something similar for ios. Currently, on iOS I am able to import the html file and just pass it as source. However, for Android I must use your method. Is there really no way to do my method in Android?Tingly

© 2022 - 2024 — McMap. All rights reserved.