0

我试图让滚动事件返回以从 webview 做出反应。根据文档,似乎要走的路是使用 postMessage 和注入的Javascript。

这是我的代码

  <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
  />

onMessage 部分似乎正在做某事,因为我在每个滚动事件的日志中都得到了这个,但是没有方向

{"isTrusted":true}

我错过了什么?

4

1 回答 1

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?

于 2020-01-28T10:56:28.953 回答