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

React Native中如何让WebView内所有URL不跳转至外部浏览器

解决React Native WebView内新窗口跳转问题

问题核心是page1里的按钮用target="_blank"触发新窗口跳转时,默认会被外部浏览器接管,要实现内部加载,按以下步骤修改:

  1. 拦截前端的新窗口请求
    给WebView注入JS代码,重写window.open方法,把跳转URL传递给RN端,而非直接打开外部窗口。

  2. RN端接收消息并在当前WebView加载新页面
    通过onMessage监听前端发来的URL,调用WebView的方法在内部加载page2。

修改后的完整代码:

import React, { useRef } from 'react';
import { WebView } from 'react-native-webview';
import Loading from './Loading';

const MyWebView = () => {
  const webViewRef = useRef(null);
  const domain = "你的实际域名前缀"; // 替换成page1/page2所在的域名

  // 注入JS拦截window.open
  const injectScript = `
    window.open = function(url) {
      window.ReactNativeWebView.postMessage(JSON.stringify({type: 'newWindow', url: url}));
      return false;
    };
  `;

  return (
    <WebView
      ref={webViewRef}
      scalesPageToFit
      startInLoadingState={true}
      renderLoading={() => <Loading />}
      source={{ uri: "url to page1" }}
      onShouldStartLoadWithRequest={(request) => {
        return request.url.startsWith(domain);
      }}
      onMessage={(event) => {
        const data = JSON.parse(event.nativeEvent.data);
        if (data.type === 'newWindow' && data.url) {
          // 两种加载方式选其一:
          // 方式1:用loadUrl加载,保留WebView历史栈
          webViewRef.current?.loadUrl(data.url);
          // 方式2:通过JS注入修改location,和前端跳转行为一致
          // webViewRef.current?.injectJavaScript(`window.location.href = '${data.url}';`);
        }
      }}
      injectedJavaScript={injectScript}
      style={styles.web}
      javaScriptEnabledAndroid={true}
      javaScriptEnabled={true}
      originWhitelist={[`${domain}*`]}
    />
  );
};

export default MyWebView;

关键说明

  • 重写window.open:前端页面里所有通过window.open触发的跳转,都会被拦截并把URL发送给RN,阻止默认的外部浏览器跳转。
  • onMessage处理逻辑:RN端拿到URL后,直接在当前WebView实例里加载,实现内部跳转的效果。
  • 域名白名单:确保originWhitelist和onShouldStartLoadWithRequest的判断覆盖page2的域名,避免被拦截。

内容的提问来源于stack exchange,提问作者jagadeesh kumar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 22:01:19