简体   繁体   English

反应原生 webview 中的事件监听器

[英]EventListener in react native webview

I am trying to get a scroll event back to react from a webview.我正在尝试让滚动事件返回以从 web 视图中做出反应。 According to the doc it seems that the way to go is using postMessage and injectedJavascript.根据文档,似乎要走的路是使用 postMessage 和注入的Javascript。

Here is my code这是我的代码

  <CustomWebView
    injectedJavaScript="window.addEventListener('scroll', function(event) {window.ReactNativeWebView.postMessage(JSON.stringify(event));});true;"
    onMessage={event => {
      console.log(event.nativeEvent.data);
    }}
    applicationNameForUserAgent="App"
    ignoreSslError
    useWebKit
    source={{ uri: net.uri }}
    startInLoadingState
  />

The onMessage part seems to be doing something because I am getting this in the logs for every scroll event, however no direction onMessage 部分似乎正在做某事,因为我在每个滚动事件的日志中都得到了这个,但是没有方向

{"isTrusted":true}

What have I missed?我错过了什么?

You can't serialize an event object with JSON.stringify.您不能使用 JSON.stringify 序列化event对象。 But, you can create json with values which you require and send it via postmessage like this:但是,您可以使用您需要的值创建 json 并通过postmessage发送它,如下所示:

    injectedJavaScript="
       var lastScrollTop = 0;
       var jsonObj = {};
       window.addEventListener('scroll', function(event) {
          jsonObj["type"] = "scroll";
          jsonObj["pageYOffset"] = window.pageYOffset; //you can add more key-values to json like this
          let scrollTopValue = window.pageYOffset || document.documentElement.scrollTop;
          jsonObj["direction"] = (scrollTopValue > lastScrollTop) ? "down" : "up";  
          lastScrollTop = scrollTopValue <= 0 ? 0 : scrollTopValue;

          window.ReactNativeWebView.postMessage(JSON.stringify(jsonObj));
     });true;"

Here is the link to find more information about stringify Event object: How to stringify event object?这是查找有关 stringify Event object 的更多信息的链接: How to stringify event object?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM