estk
V2EX  ›  React

React Native Webview 监听网页内部资源加载的探索

  •  
  •   estk · Nov 5, 2022 · 1585 views
    This topic created in 1283 days ago, the information mentioned may be changed or developed.

    React Native Webview 组件没有自带的方式可以监听网页内部资源的加载( jpg, png, js, css, mp3 等),曲线实现方式:用 js 注入定时器到网页,网页里获取节点的 src 属性并 postMessage 给 native ,以 img 节点为例:

    import { WebView } from 'react-native-webview'
    let srcs:string[] = []
    export default function WebviewScreen() {
      return (
        <WebView 
          source={{ uri: 'https://www.bing.com/images' }}
          useWebKit={true}
          allowsBackForwardNavigationGestures
          allowsInlineMediaPlayback
          injectedJavaScriptBeforeContentLoaded = {`
            setInterval(()=>{
              const nodes = document.querySelectorAll('img')
              for (const node of nodes) {
                window.ReactNativeWebView.postMessage(node.src)
              }
            }, 2000)
          `}
          onMessage = {msg=>{
            const src = msg.nativeEvent?.data?.trim()
            if (src && -1===srcs.indexOf(src)) {
              console.log('onMessage', new Date(), src)
              srcs.push(src)
            }
          }}
        />
      );
    }
    

    也可以用于 video 等其它带有 src 的节点

    缺点:

    1. 只能定时不能监听
    2. 如果 crc 属性里是 blob:// 则会得到空字符串
    No Comments Yet
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5640 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 08:35 · PVG 16:35 · LAX 01:35 · JFK 04:35
    ♥ Do have faith in what you're doing.