0

I am trying to get a scroll event back to react from a webview. According to the doc it seems that the way to go is using postMessage and injectedJavascript.

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

{"isTrusted":true}

What have I missed?

Mel
  • 625
  • 9
  • 25

1 Answers1

0

You can't serialize an event object with JSON.stringify. But, you can create json with values which you require and send it via postmessage like this:

    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?

Ankit Makwana
  • 2,291
  • 12
  • 16