Search code examples
react-nativereact-native-webview

how to clear local storage of react-native-webview?


how to clear localStorage of react-native-webview and

what is the best way to clear localstorage of webview


Solution

  • we can use injectedJavaScript to clear localstorage. we can call this.clearLocalStorage(); to clear localStorage

    clearLocalStorage = () => {
        this.setState({ isCookieClear: true }, () => {
          setTimeout(() => {
            this.setState({ isCookieClear: false });
          }, 2000);
        });
      };
    
    const {isCookieClear}=this.state;
    
    let myInjectedJs = `(function(){
      ${isCookieClear?`window.localStorage.clear(); `:''}
    })();`
    
    return (
    <WebView
     ref="webview"
     javaScriptEnabled={true}
     domStorageEnabled={true}
     injectedJavaScript={myInjectedJs}
     useWebKit={true}
     />
    )