React Native WebView:injectJavascript注入全局变量的正确写法
injectJavaScript Function for Global Variables Hey there! I ran into this exact issue a while back—turns out the newer versions of react-native-webview require injectJavaScript to be a function that returns a string of executable JS, not just a raw string. Let me walk you through how to set this up properly to pass global variables to your loaded webpage.
Basic Implementation
First, here's a straightforward example where we inject a global object into the webpage. The function will return a JS string that defines your global variable on the window object:
import React from 'react'; import { WebView } from 'react-native-webview'; const CustomWebView = () => { // Define the data you want to pass as a global variable const appGlobalState = { userId: 'user_789', appVersion: '1.2.3', isLoggedIn: true }; // The inject function: returns executable JS string const injectGlobalVariables = () => { // Use JSON.stringify to safely convert JS objects to valid JS syntax return ` // Define your global variable on the window object window.myAppGlobals = ${JSON.stringify(appGlobalState)}; // Optional: Log to confirm injection (check webpage's dev tools) console.log('Injected global variables:', window.myAppGlobals); `; }; return ( <WebView source={{ uri: 'https://your-target-webpage.com' }} // Pass the function here (don't call it, just reference it!) injectJavaScript={injectGlobalVariables} // Make sure JS is enabled in the WebView javaScriptEnabled={true} /> ); }; export default CustomWebView;
Key Notes:
- Function Requirement: The
injectJavaScriptprop expects a function that returns a string of JavaScript code. If you pass a raw string directly, you'll get that error you saw. - Safe Data Handling: Always use
JSON.stringifyfor objects/arrays to avoid syntax errors when injecting into the webpage. - Accessing the Variable: Once injected, your webpage can access the global variable directly via
window.myAppGlobals(or whatever name you choose).
Updating Variables Dynamically
If you need to update the global variable later (like when your React state changes), use a ref to call injectJavaScript directly on the WebView instance:
import React, { useRef, useEffect, useState } from 'react'; import { WebView } from 'react-native-webview'; const DynamicWebView = () => { const webViewRef = useRef(null); const [userTheme, setUserTheme] = useState('light'); // Initial injection const initialInject = () => ` window.userTheme = "${userTheme}"; `; // Update injection when theme changes useEffect(() => { if (webViewRef.current) { const updateCode = ` window.userTheme = "${userTheme}"; // Optional: Trigger a callback in the webpage if needed if (window.onThemeUpdate) window.onThemeUpdate(window.userTheme); `; webViewRef.current.injectJavaScript(updateCode); } }, [userTheme]); return ( <> <button onPress={() => setUserTheme(userTheme === 'light' ? 'dark' : 'light')}> Toggle Theme </button> <WebView ref={webViewRef} source={{ uri: 'https://your-webpage.com' }} injectJavaScript={initialInject} javaScriptEnabled={true} /> </> ); }; export default DynamicWebView;
This way, whenever your React state changes, you can push updated values to the webpage's global scope.
内容的提问来源于stack exchange,提问作者Jon_B

