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.
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.
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.
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';
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.
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.
myInjectedJs
in WebView.<WebView
ref={webView => { this.refWeb = webView; }}
javaScriptEnabled={true}
injectedJavaScript={myInjectedJs}
...
Hope this solves your problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With