You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 to true—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 useEffect to 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:10:46