Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native - Set localStorage in WebView

I would like to set localStorage in the WebView component before loading the page.

https://facebook.github.io/react-native/docs/webview

My use case for this is that my RN app would like to open a page on it's accompanying website. The website authenticates on load by checking for a token in localStorage. If the token isn't there they will be prompted to login. Seen as the user has already logged in on the app I would prefer it if they could avoid logging in again in the WebView.

like image 456
Ben McAlindin Avatar asked Mar 09 '19 13:03

Ben McAlindin


People also ask

How do you pass data from React Native to WebView?

Now, let's send data from a React Native app to WebView. Create a function called webviewRef and attach it to the WebView component. Next, create a function called sendDataToWebView and add the code below to it. Inside the “script” tag, use window.

Can we use local storage in React Native?

Introduction to React Native Local StorageIt also supports local storage for this purpose. We should not confuse the data stored with the state data as it is not a replacement for that. State Data always gets erased once the app is closed. Local Storage can also be achieved by Async Storage.

How add load in WebView in React Native?

Adding a loading spinner to React Native Webview For this, we need to import the ActivityIndicator component from the react-native package as shown in the code snippet below: import { Text, View, StyleSheet, ActivityIndicator } from 'react-native';


1 Answers

You might have overcome the issue. If not here is my solution.

You can use injectedJavaScript property of WebView and add javascript code to add the token on page load.

Example code snippet.

  1. My Custom Javascript code that i need to inject.
let myInjectedJs = `(function(){ let tk = window.localStorage.getItem('tokenKey');
      if(!tk || (tk && tk != '${token}')){
        window.localStorage.setItem('tokenKey', '${token}');
        window.location.reload();
      }
    })();`;

Code Explanation

Function is called as soon as loaded. Checks if tokenKey is already set. If not set we are setting it to the new token ${token} and reloading the page.

Note: We need to pass function as a string to injectedJavaScript in webview.

  1. Using myInjectedJs in WebView.
<WebView
    ref={webView => { this.refWeb = webView; }}
    javaScriptEnabled={true}
    injectedJavaScript={myInjectedJs}
    ...

Hope this solves your problem.

like image 126
user1177755 Avatar answered Nov 15 '22 07:11

user1177755