some images don't work on Webview React Native

Viewed 24

I'm loading a site through webview, but some images don't work, I went to analyze and saw that the images that don't work the attr changed from src to data-src. the problem is that on my site this is not so.

enter image description here


<WebView
    onLoad={() => setLoading(false)}
    source={{ uri: url || `${ENV.WEBVIEW_URL}${route}` }}
    style={{
        width,
        display: loading ? 'none' : 'flex',
        backgroundColor: theme.base.background,
    }}
    injectedJavaScriptBeforeContentLoaded={myInjectedJsBeforeContentLoaded}
    onMessage={(event) =>
        onMessage ? onMessage(JSON.parse(event.nativeEvent.data)) : {}
    }
    ref={webviewRef}
/>

1 Answers

You can use a workaround using the injectJavascript property:

const changeDataSrcJavascript = `
   var imageElements = document.querySelectorAll('img');
    
   imageElements.forEach(c=> c.setAttribute('src', c.getAttribute('data-src')));
`;

  return (
    <WebView
      injectedJavaScript={changeDataSrcJavascript}
      ...
    />
  );
Related