The page I want to open at React Native app requires checking the localStorage, which stores the user token, user roles, and user permissions. Therefore, it is necessary to set the token and other relevant values in the localStorage before loading the page.
I use the prop injectedJavaScriptBeforeContentLoaded in react-native-webview but didn't work.
Here is my code
const runFirst = `
window.localStorage.setItem('api_token', 'zzz');
window.localStorage.setItem('auth_roles', 'zzz');
window.localStorage.setItem('auth_permissions', 'zzz');
setTimeout(function() { window.alert('hi') }, 1000);
true; // note: this is required, or you'll sometimes get silent failures
`;
return (
<NativeBaseProvider>
<WebView
startInLoadingState={true}
source={{
//uri: 'https://github.com/react-native-webview/react-native-webview',
uri:'xxxxxx'
}}
injectedJavaScriptBeforeContentLoaded={runFirst}
onMessage={(event) => {}}
style={{width:screenWidth, height:screenHeight}}
/>
</NativeBaseProvider>
);
The code
setTimeout(function() { window.alert('hi') }, 1000);
will be execute but the
window.localStorage.setItem
didn't be execute.
and the page be opened is blank.
If I remove the code about window.localSotrage.setItem , the page be open will be normal.
Device: Samsung Galaxy A34 5G
OS: Android
OS version: android 9
react-native version: 0.71.13
react-native-webview version: 13.6.2
I have tried and read the resource about React-Native-WebView injectedJavaScriptBeforeContentLoaded:
I looking for some solution or help
Have you tried waiting until the document is loaded before accessing
localStorage?Maybe the alert works because of the timeout.