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.

Desmond Chen
  • 95
  • 1
  • 4

1 Answers1

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

Ankit Makwana
  • 2,291
  • 12
  • 16
  • 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? – SeanMC Dec 01 '21 at 15:33