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

React Native中如何调用WebView内的多个JavaScript函数

React Native 侧调用 WebView 内自定义JS函数实现方案

你在HTML里定义的setColor、setBackgroundColor属于页面window全局作用域下的函数,只要在页面加载完成后,直接在注入脚本里写函数调用语句即可访问,根据不同的触发需求,对应实现方式如下:

方式1:页面加载完成后自动执行函数

如果需要WebView加载完页面就自动触发这两个函数,直接把调用逻辑写到injectedJavaScript属性里即可:

<WebView
  injectedJavaScript={`
    // 直接调用全局函数
    setColor();
    setBackgroundColor();
    // iOS端要求注入脚本最后必须返回真值,否则会抛错
    true;
  `}
  javaScriptEnabled={true}
  domStorageEnabled={true}
  scalesPageToFit={true}
  scrollEnabled={false}
  // 加载你自己的HTML页面,本地/远程地址均可
  source={{ uri: '你的页面地址' }}
/>

方式2:RN侧交互按需触发函数

如果需要在RN侧点击按钮、满足某个业务条件时再主动调用WebView内的函数,需要给WebView绑定ref,通过实例上的injectJavaScript方法动态注入执行脚本,完整示例如下:

import React, { useRef, useState } from 'react';
import { WebView } from 'react-native-webview';
import { View, Button } from 'react-native';

export default function WebViewPage() {
  const webViewRef = useRef(null);
  // 标记WebView是否加载完成,避免提前调用报错
  const [isWebLoaded, setIsWebLoaded] = useState(false);

  const triggerSetColor = () => {
    if (!isWebLoaded) return;
    webViewRef.current.injectJavaScript(`
      setColor();
      true;
    `);
  };

  const triggerSetBgColor = () => {
    if (!isWebLoaded) return;
    webViewRef.current.injectJavaScript(`
      setBackgroundColor();
      true;
    `);
  };

  return (
    <View style={{ flex: 1 }}>
      {/* RN侧操作按钮 */}
      <View style={{ padding: 12, flexDirection: 'row', gap: 8 }}>
        <Button title="触发setColor" onPress={triggerSetColor} />
        <Button title="触发setBackgroundColor" onPress={triggerSetBgColor} />
      </View>
      <WebView
        ref={webViewRef}
        javaScriptEnabled={true}
        domStorageEnabled={true}
        scalesPageToFit={true}
        scrollEnabled={false}
        // 页面加载完成后修改标记位
        onLoadEnd={() => setIsWebLoaded(true)}
        // 示例直接写入提供的HTML代码,实际项目替换成自己的页面地址即可
        source={{
          html: `<html lang="en">
<head>
</head>
<body>
    <div id="container" style="width: 100%; height: 100%;"></div>
</body>
<script>
    function setColor() {
        alert('set color...')
    }

    function setBackgroundColor() {
        alert('set background color ...')
    }
</script>
</html>`
        }}
      />
    </View>
  );
}

关键注意事项

  • 所有注入到WebView执行的脚本,末尾必须加true;语句,否则iOS平台会出现脚本执行失败、无响应的问题。
  • 必须等WebView页面加载完成后再调用函数,否则会报「函数未定义」的错误,可以通过onLoadEnd事件做加载状态标记。
  • HTML中直接在script标签顶层定义的函数,默认会挂载到window全局作用域,不需要额外做绑定即可直接调用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 22:24:16