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

React Native WebView部分图片无法加载:图片属性src变为data-src

解决WebView加载网站图片src变为data-src导致无法显示的问题

问题分析

部分图片无法显示是因为网站的懒加载逻辑(或针对WebView的适配逻辑)将图片真实地址存储在data-src属性中,未自动赋值给src,而WebView环境没有触发原网站的图片加载触发逻辑。

解决方案

1. 注入JS代码替换图片属性

修改WebView的注入JS,添加DOM处理逻辑,将所有data-src的值同步到src:

首先编写注入的JS代码:

// 等待DOM加载完成后处理图片
document.addEventListener('DOMContentLoaded', () => {
  // 选中所有带data-src的图片
  const lazyImages = document.querySelectorAll('img[data-src]');
  lazyImages.forEach(img => {
    // 将data-src赋值给src
    img.src = img.getAttribute('data-src');
    // 可选:移除data-src属性
    img.removeAttribute('data-src');
  });
});

然后将这段代码整合到你的WebView配置中,示例如下:

<WebView
    onLoad={() => setLoading(false)}
    source={{ uri: url || `${ENV.WEBVIEW_URL}${route}` }}
    style={{
        width,
        display: loading ? 'none' : 'flex',
        backgroundColor: theme.base.background,
    }}
    injectedJavaScript={`
        document.addEventListener('DOMContentLoaded', () => {
          const lazyImages = document.querySelectorAll('img[data-src]');
          lazyImages.forEach(img => {
            img.src = img.getAttribute('data-src');
            img.removeAttribute('data-src');
          });
        });
        ${myInjectedJsBeforeContentLoaded || ''}
    `}
    onMessage={(event) =>
        onMessage ? onMessage(JSON.parse(event.nativeEvent.data)) : {}
    }
    ref={webviewRef}
    javaScriptEnabled={true} // 确保JS功能开启,显式声明更稳妥
/>

2. 触发网站原生懒加载逻辑(可选)

如果网站的懒加载是通过滚动触发的,可注入滚动事件模拟用户操作,触发图片加载:

// 在DOM加载完成后执行滚动
document.addEventListener('DOMContentLoaded', () => {
  // 滚动到底部再回到顶部,触发懒加载检测
  window.scrollTo(0, document.body.scrollHeight);
  setTimeout(() => {
    window.scrollTo(0, 0);
  }, 500);
});

将这段代码和上面的图片属性替换代码合并即可。

3. 检查权限与安全策略限制

如果图片仍无法加载,需确认WebView是否开启了必要权限(如allowFileAccess、allowUniversalAccessFromFileURLs,根据平台调整),同时排查网站的Content-Security-Policy是否限制了图片资源的加载。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 00:45:40