javascript - 反应本机webview中的EventListener
问题描述
我试图让滚动事件返回以从 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}
我错过了什么?
解决方案
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?
推荐阅读
- python - Django migrate --fake-initial 报告关系已经存在
- three.js - 如何在 Autodesk Forge 中动态更新 THREE.js PointCloud 覆盖
- android - 如何在 Android 中保存和重新创建布局?
- c - 将大型 CSV 文件汇总到数组中的内存访问冲突
- java - 在某些情况下无法打印正确的结果
- solidity - 使用 web3 v1.0 发送原始交易的无效类型错误
- reactjs - React Router 5 不使用查询参数/状态重定向(剥离查询参数/状态)
- python - 如何使用 Python 制作字数计数器程序?
- c# - 从字符串 C# 中查找并提取一个数字
- c - 读取文件并将数据保存到二维数组中