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

如何从端点获取脚本并在React Native中使用其返回变量?

在React Native中获取并解析Web API返回的自执行脚本

核心思路

Web端通过<script>标签加载时会自动执行自执行函数并生成变量,React Native中需要手动获取脚本文本,再通过执行或解析的方式提取目标对象。


方案一:直接执行脚本(简单但需注意安全)

如果API是可信的,可以直接执行获取到的脚本文本,然后访问生成的变量:

fetch("https://example.com/index.js", { method: "GET" })
  .then(response => response.text())
  .then(scriptText => {
    // 执行脚本
    eval(scriptText);
    // 访问生成的变量
    console.log(Script.some); // 输出 "method"
    console.log(Script.another); // 输出 "method"
  })
  .catch(error => console.error("获取或执行脚本失败:", error));

注意:eval会执行任意代码,若API返回的脚本不可信,存在安全风险,不推荐在生产环境使用此方案。


方案二:解析脚本文本提取对象(更安全)

如果不想执行未知代码,可以通过正则表达式提取自执行函数的返回内容,再转换为JavaScript对象:

fetch("https://example.com/index.js", { method: "GET" })
  .then(response => response.text())
  .then(scriptText => {
    // 匹配自执行函数中的返回对象
    const match = scriptText.match(/\(\(\) => \{[\s\S]*return\s+({[\s\S]*});[\s\S]*\}\)\(\);/);
    if (match && match[1]) {
      // 将匹配到的对象字符串转换为JS对象
      const scriptObj = JSON.parse(match[1].replace(/(\w+):/g, '"$1":'));
      console.log(scriptObj.some); // 输出 "method"
      console.log(scriptObj.another); // 输出 "method"
    } else {
      console.error("无法解析脚本内容");
    }
  })
  .catch(error => console.error("获取脚本失败:", error));

说明:

  • 正则表达式会匹配自执行函数中return后的对象内容
  • 使用replace是为了将对象中的无引号键转换为带引号的JSON格式,确保JSON.parse能正常解析
  • 此方案避免执行未知代码,安全性更高,但需要确保脚本的结构稳定,若API返回的脚本格式变化,正则可能失效

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 08:32:46