Nabil Mustofa
Nabil Mustofa

Reputation: 72

How to disable the Page Visibility API of react native webview?

I am trying to create a simple Brave-like browser that can play YouTube videos when the app is in the background. I've tried many other options, but I think the best way is to disable the page visibility API of the webview itself so that it does not send the app visibility signal to the website. I've tried to inject JS code to do this, but it's not working. Is there any other way in React Native, like customizing the webview native code to disable the visibility API? I am not using Expo. It's a React Native CLI project.

import React from 'react';
import { StyleSheet, View } from 'react-native';
import { WebView } from 'react-native-webview';

const App = () => {
  const injectedJavaScriptBeforeContentLoaded = `
    Object.defineProperty(document, 'hidden', { value: false });
    Object.defineProperty(document, 'visibilityState', { value: 'visible' });
    document.addEventListener('visibilitychange', function(event) {
      event.stopImmediatePropagation();
    }, true);
  `;

  return (
    <View style={styles.container}>
      <WebView
        source={{ uri: 'https://www.youtube.com' }}
        injectedJavaScriptBeforeContentLoaded={injectedJavaScriptBeforeContentLoaded}
        mediaPlaybackRequiresUserAction={false}
        allowsInlineMediaPlayback={true}
        javaScriptEnabled={true}
        domStorageEnabled={true}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
});

export default App;

Upvotes: 0

Views: 20

Answers (0)

Related Questions