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

iOS设备中React Native Webview的injectJavascript注入不生效如何解决

React Native WebView iOS端注入JS不生效修复方案

核心问题原因

  1. 语法错误:原代码中WebView的source.uri参数值为字符串,未添加引号,会导致运行异常
  2. 注入时机不符:injectedJavaScript属性默认在页面加载完成后才执行注入,若要提前注入需使用对应前置注入属性
  3. iOS平台限制:iOS端react-native-webview默认拦截所有JS弹窗(alert/confirm/prompt),未手动配置回调的情况下弹窗不会触发
  4. 同源策略限制:iOS端WebView默认开启严格同源策略,未配置读写权限的情况下注入的跨域JS可能被拦截

具体修复步骤

  • 修正source.uri的字符串引号语法
  • 将injectedJavaScript替换为injectedJavaScriptBeforeContentLoaded,实现页面内容加载前注入JS
  • 添加onAlert回调处理JS的window.alert调用,实现iOS端弹窗正常弹出
  • 新增allowingReadAccessToURL属性放开iOS端跨域访问限制

修复后完整代码

import React from 'react';
import { View, ActivityIndicator, Alert } from 'react-native';
import { WebView } from 'react-native-webview';
import styles from '../../styles';

export default function Links() {

  function LoadingIndicatorView() {
    return (
      <View style={styles.hubLoading}>
        <ActivityIndicator color='#009b88' size='large' />
      </View>
    )  
  }

  const runFirst = `
      setTimeout(function() { window.alert('hi') }, 2000);
      true;
  `

  return (
    <WebView 
      source={{ uri: "https://www.google.com/" }} 
      renderLoading={LoadingIndicatorView} 
      startInLoadingState={true} 
      javaScriptEnabled={true}
      injectedJavaScriptBeforeContentLoaded={runFirst}
      allowingReadAccessToURL="*"
      onAlert={(event) => {
        Alert.alert("提示", event.nativeEvent.message);
        return true;
      }}
    />
  );
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.22 02:45:03