react-native-webview的console.log直接打印到控制台

在react-native-webview11.17.2 中
WebView组件和html交互不能直接使用window.postMessage要改用window.ReactNativeWebView.postMessage方法

首先重写webview里的console.log
(这里的_.get是lodash库的一个取值方法)

const onError = () => {
  console.error('出错了!')
}
const _postMessage = (...params) => {
  const reactNativeWebView = _.get(window, 'ReactNativeWebView')
  const _postMessage = _.get(reactNativeWebView, 'postMessage', onError)
  _postMessage.call(reactNativeWebView, JSON.stringify(params))
}
console.log = (() => {
    const target = console.log
    const { ReactNativeWebView } = window
    return (...args) => {
      if (ReactNativeWebView) {
        return _postMessage.call(console, ...args)
      } else {
        return target.call(console, ...args)
      }
    }
  })()

我们先把旧的console.log用闭包保存在内存里,然后判断是否处于ReactNative的WebView里,如果是则调用postMessage向React Native发送信息。也可以用这个方法判断当前环境是否为开发环境之类的

在React Native中我们可以直接接受到stringify后的参数。再转换一次就可以打印到控制台了,因为console.log会有多个参数。所以我们这里使用了延展运算符

  const _onMessage = (e: WebViewMessageEvent) => {
    const data = _.get(e, 'nativeEvent.data', '[]');
    const args = JSON.parse(data)
    console.log('webview -->', ...args);
  };
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容