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

React Native中加载script标签及从返回script内容中提取URL的方法

React Native 加载 script 标签解决方案

react-native-render-html 本身不支持执行 script 标签,该库的核心能力是将 HTML 标签转换为 React Native 原生视图组件,没有内置浏览器 JS 执行环境,无法运行 JS 代码。如果需要执行包含 script 的 HTML 内容,请使用 react-native-webview 组件渲染,它自带浏览器内核可以正常执行 JS 逻辑,示例代码如下:

// 先安装依赖:npm install react-native-webview 或 yarn add react-native-webview
import { WebView } from 'react-native-webview';

const App = () => {
  // 从接口获取到的原始HTML字符串
  const rawHtml = "<script>window.location.replace(\"https://www.google.com\");</script>";
  return <WebView source={{ html: rawHtml }} javaScriptEnabled={true} />
}
从返回内容中提取动态URL

可以通过HTML转义+正则匹配的方式提取URL,示例代码如下:

// 接口返回的原始响应内容
const apiResponse = "\"&lt;script&gt;window.location.replace(\\\"https://www.google.com\\\");&lt;/script&gt;\\r\\n\"";
// 第一步:解码转义的HTML字符
const decodedHtml = apiResponse.replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/\\"/g, '"');
// 第二步:正则匹配window.location.replace内的URL
const urlRegex = /window\.location\.replace\(["']([^"']+)["']\)/;
const matchResult = decodedHtml.match(urlRegex);
// 提取到的URL存储到targetUrl变量,匹配失败则为null
const targetUrl = matchResult ? matchResult[1] : null;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 09:54:03