When using a UIWebView
with editable content, the user can type their own text on the editable DIV.
Is there a way to fire an event on the ViewController every time the user changes the editable text (similar to the UITextField
value change event)?
The ViewController needs to know when the user has changed to the text for two reasons; to know if the user entered any text at all, and to resize the UIWebView as the content text grows.
The UIWebView
delegate doesn't seem to include this type of event. This will probably have to be done via Javascript but can't seem to find the answer out there. Help!
There is no direct way to listen to events from UIWebView, but you can bridge them. Since iOS7 it is pretty easy as there is JavaScriptCore.framework (you need to link it with project):
JSContext *ctx = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
ctx[@"myUpdateCallback"] = ^(JSValue *msg) {
[self fieldUpdated];
};
[ctx evaluateScript:@"document.getElementById('myEditableDiv').addEventListener('input', myUpdateCallback, false);"];
(I have no possibility at the moment to test the code, but I hope it works)
Before iOS7 (if you want to support lower version you have to use this) it was a bit more tricky. You can listen on webView delegate method webView:shouldStartLoadWithRequest:navigationType:
for some custom scheme, ex:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
if ([request.URL.scheme isEqualToString:@"divupdated"]) {
[self fieldUpdated];
return NO;
}
return YES;
}
and fire something like this on webView:
[webView stringByEvaluatingJavaScriptFromString:@"document.getElementById('myEditableDiv').addEventListener('change', function () {"
@"var frame = document.createElement('iframe');"
@"frame.src = 'divupdated://something';"
@"document.body.appendChild(frame);"
@"setTimeout(function () { document.body.removeChild(frame); }, 0);"
@"}, false);"];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With