我有一个使用自定义undo和redo的WKWebView。我想知道何时系统触发undo/redo(通过手势或在iPadOS上点击键盘助手按钮),以便我可以使用自己的自定义实现。
是否有公共API可以做到这一点?
有多种方法。在iOS本地端,据我所知没有公共API可用于完全控制,但您可以像这样监听UNDO通知以了解它们:
[NSNotificationCenter.defaultCenter addObserverForName:NSUndoManagerWillUndoChangeNotification object:nil queue:NSOperationQueue.mainQueue usingBlock:^(NSNotification * _Nonnull note) {
NSLog(@"Undo Notification: %@", note);
}];
然后您会发现负责此事的NSUndoManager位于WKContentView
中。要到那里只有使用已知风险的函数交换才能帮助...
但是在基于 WebKit 的浏览器视图中(如 WKWebView
),还有另一种方法可以实现,那就是监听 beforeinput
事件。例如,对于一个 contenteditable
元素,您可以添加以下侦听器:
editor.addEventListener('beforeinput', event => {
if (event.inputType === 'historyUndo') {
console.log('undo')
event.preventDefault()
}
if (event.inputType === 'historyRedo') {
console.log('redo')
event.preventDefault()
}
console.log('some other inputType', event.inputType)
})
这个想法来自于这个讨论:https://discuss.prosemirror.net/t/native-undo-history/1823/3?u=holtwick
这里有一个 JSFiddle 进行测试:https://jsfiddle.net/perenzo/bhztrgw3/4/
还可以看看相应的 TipTap 插件:https://github.com/scrumpy/tiptap/issues/468