React Native中如何从WebView中获取当前加载页面的URL?
React Native WebView 获取当前加载页面URL的实现方案
以下方法均基于社区维护的react-native-webview包,React Native核心库自带的旧版WebView已在0.60版本后停止维护,建议先迁移到社区版再使用对应API。
- 方式1:监听导航状态变化实时获取
使用onNavigationStateChange回调,该回调会在页面首次加载、跳转、前进后退等所有导航状态变更时触发,返回的参数直接包含当前URL字段:
import WebView from 'react-native-webview'; import { useState } from 'react'; const CustomWebView = () => { // 存储当前页面URL const [currentUrl, setCurrentUrl] = useState(''); return ( <WebView source={{ uri: 'https://example.com' }} onNavigationStateChange={(navState) => { // navState.url 即为当前加载页面的最新URL setCurrentUrl(navState.url); }} /> ); };
- 方式2:在页面加载生命周期节点获取
如果只需要在页面加载完成、加载结束等特定节点获取URL,可以使用onLoad、onLoadEnd等生命周期回调,从nativeEvent中提取URL:
<WebView source={{ uri: 'https://example.com' }} onLoad={(event) => { const currentUrl = event.nativeEvent.url; console.log('页面加载完成,URL为:', currentUrl); }} />
- 方式3:主动触发获取当前URL
如果需要在特定用户操作(比如点击按钮)时主动拉取当前URL,可以绑定WebView的ref,调用社区版内置的getCurrentUrl()异步方法:
import WebView from 'react-native-webview'; import { useRef, Button } from 'react'; const CustomWebView = () => { const webViewRef = useRef(null); const getUrl = async () => { const url = await webViewRef.current?.getCurrentUrl(); console.log('当前页面URL:', url); }; return ( <> <WebView ref={webViewRef} source={{ uri: 'https://example.com' }} /> <Button title="获取当前页面URL" onPress={getUrl} /> </> ); };
注意:如果页面存在iframe嵌套,上述默认方法获取的是外层主页面的URL,若需要获取iframe内的URL,需要通过
injectJavaScript注入JS代码主动监听iframe的导航事件再回传给RN层。
内容的提问来源于stack exchange,提问作者Maee
相关产品推荐
相关产品推荐

