Skip to content Skip to sidebar Skip to footer

How To Prevent React Native Android Webview From Running Youtube In The Background?

My app was rejected in play store for 'make sure it doesn't enable background play of YouTube videos'. I used the basic Webview component and loaded a youtube page. After playing t

Solution 1:

You could use AppState from react-native: documentation.

And show the webview (which contains your YouTube embed) only if the app state is 'active'

importReact, {Component} from'react'import {AppState, WebView} from'react-native'classAppStateExampleextendsComponent {

  state = {
      appState: AppState.currentState
  }

  componentDidMount() {
      AppState.addEventListener('change', this._handleAppStateChange);
  }

  componentWillUnmount() {
      AppState.removeEventListener('change', this._handleAppStateChange);
  }

  _handleAppStateChange = (nextAppState) => {        
      this.setState({appState: nextAppState});
  }

  render() {

    return (

      {this.state.appState == 'active' &&
           <WebView />
      }

    )

  }

}

This is good if you are working with Expo, no need to touch any native code.

Solution 2:

Ok, so i ended up creating my own MyReactWebViewManager:

publicclassMyReactWebViewManagerextendsSimpleViewManager<WebView> {

privatestaticfinalStringREACT_CLASS="RCTMyWebView";

....

And in it, i created MyReactWebView with the following onHostPause override:

privatestaticclassMyReactWebViewextendsWebViewimplementsLifecycleEventListener { 
    ...

    @OverridepublicvoidonHostResume() {
        // do nothingLog.i(REACT_CLASS,"onHostResume");
        this.onResume();
    }

    @OverridepublicvoidonHostPause() {
        // do nothingLog.i(REACT_CLASS,"onHostPause");
        this.onPause();
    }

Hopefully, this will be handled by react-native in the future.

Solution 3:

Simply add this prop to the web view

mediaPlaybackRequiresUserAction={true}

<WebViewmediaPlaybackRequiresUserAction={true}
 />

Post a Comment for "How To Prevent React Native Android Webview From Running Youtube In The Background?"