V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
estk
V2EX  ›  React

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

  •  
  •   estk · 2022-11-05 17:32:45 +08:00 · 971 次点击
    这是一个创建于 529 天前的主题,其中的信息可能已经有所发展或是发生改变。

    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:// 则会得到空字符串
    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5396 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 38ms · UTC 08:37 · PVG 16:37 · LAX 01:37 · JFK 04:37
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.