How can i monitor requests on WKWebview?
I'v tried using NSURLprotocol (canInitWithRequest) but it won't monitor ajax requests (XHR), only navigation requests(document requests)
How can i monitor requests on WKWebview?
I'v tried using NSURLprotocol (canInitWithRequest) but it won't monitor ajax requests (XHR), only navigation requests(document requests)
If you have control of the content inside the
WkWebView
you can send messages to your native app usingwindow.webkit.messageHandlers
whenever you make an ajax request, which will be received as aWKScriptMessage
that can be processed by whatever you've designated as yourWKScriptMessageHandler
. The messages can contain whatever information you wish, and will be automatically converted into native objects/values in your Objective-C or Swift code.If you don't have control over the content you can still do this by injecting your own JavaScript via a
WKUserScript
to track ajax requests and send back messages using the method stated above.@Benzi Heler answer is great, but it uses jQuery which seems like is not working in
WKWebView
anymore, so I have found solution without using jQuery.Here is ViewController implementation that lets you be notified every AJAX request is completed in
WKWebView
:Pretty standard implementation. There is a
WKWebView
created programmatically. There is injected script that is loaded fromscript.js
file.And the most important part is
script.js
file:userContentController
delegate method will be called every time there is AJAX request loaded. I'm passing therestatus
andresponseURL
, because this was what I needed in my case, but you can also get more informations about request. Here is the list of all properties and methods available: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequestMy solution is inspired by this answer written by @John Culviner: https://stackoverflow.com/a/27363569/3448282
Finally I solved it
Since I don't have control over the web view content, I injected to the WKWebview a java script that include a jQuery AJAX request listener.
When the listener catches a request it sends the native app the request body in the method:
The native app catches the message in a delegate called:
and perform the corresponding actions
here is the relevant code:
ajaxHandler.js -
My ViewController delegate are:
And in my
viewDidLoad()
, I'm creating a WKWebView:Here is the addUserScriptToUserContentController: