I need to manipulate the text that is pasted into a WKWebView (from any source) running an asynchronous operation that can take some time.
My original idea was to use Javascript and the WKWebView configuration in order to get the onpaste
event:
WKUserContentController *wkUController = [[WKUserContentController alloc] init];
NSString *pasteJSSource = @"document.addEventListener('onpaste', function(){ window.webkit.messageHandlers.ComposerListener.postMessage('onpaste happened!'); })";
WKUserScript *pasteScript = [[WKUserScript alloc] initWithSource:pasteJSSource injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly: NO];
[wkUController addScriptMessageHandler:self name:@"ComposerListener"];
[wkUController addUserScript:pasteScript];
webViewConfiguration.userContentController = wkUController;
Then my class implements WKScriptMessageHandler
#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
NSLog(@"message: %@", message.body);
}
(Ignore Obj-c, swift is ok too)
But I have two problems:
userContentController:didReceiveScriptMessage:
is never called- I don't know how to intercept the pasted code and replace it with something different
Any idea on how to solve this (even without JS that I don't obviously know :P )? Thanks.