React Native:如何在WebView加载页面前设置localStorage
Hey, I've run into this exact scenario before—here's how you can pre-set localStorage in the React Native WebView so your users don't have to re-login to your companion website:
Core Approach
The key is to inject a JavaScript snippet into the WebView before the target page loads that sets the auth token directly into the WebView's localStorage. This way, when your website checks for the token on initial load, it finds the one from your app and skips the login prompt.
Step-by-Step Implementation
Here's a reusable component example that handles this:
import React, { useRef } from 'react'; import { WebView } from 'react-native-webview'; const AuthenticatedWebView = ({ userAuthToken, targetUrl }) => { const webViewRef = useRef(null); // Build the script to inject: sets your token in localStorage const injectAuthToken = ` // If your token is an object, use JSON.stringify() here window.localStorage.setItem('authToken', '${userAuthToken}'); true; // Required return value for React Native WebView `; return ( <WebView ref={webViewRef} source={{ uri: targetUrl }} // Inject the script when the WebView starts loading the page injectJavaScript={injectAuthToken} // Optional: Double-down by injecting again on load start (for edge cases) onLoadStart={() => { webViewRef.current?.injectJavaScript(injectAuthToken); }} // Ensure JavaScript is enabled (required for localStorage access) javaScriptEnabled={true} // Enable DOM storage (localStorage/sessionStorage support) domStorageEnabled={true} /> ); }; export default AuthenticatedWebView;
Key Notes
domStorageEnabled: Don't forget to set this totrue—it enables support for localStorage/sessionStorage in the WebView (some versions of React Native WebView require this explicitly).- Token Format: If your auth token is a JSON object (not a plain string), wrap it in
JSON.stringify()when injecting:window.localStorage.setItem('authToken', '${JSON.stringify(userAuthToken)}'); - Edge Cases: If you notice the token isn't being picked up consistently, you can use
useEffectto inject the script once the WebView is fully initialized:React.useEffect(() => { if (webViewRef.current) { webViewRef.current.injectJavaScript(injectAuthToken); } }, [webViewRef, injectAuthToken]);
How It Works
When the WebView loads your companion website, the injected script runs before the site's own authentication check. This populates localStorage with the token your app already has, so the site recognizes the user as logged in automatically.
内容的提问来源于stack exchange,提问作者Ben McAlindin

