WKWebView in Xamarin.iOS - How to intercept requests for resources such as CSS and JS files?

752 views Asked by At

I load an HTML file into a WKWebView on Xamarin.iOS using webView.LoadHtmlString(). This HTML file references a CSS file and a JS file, for example:

<html>
    <head>
        <link rel="stylesheet" href="https://example.com/styles.css"/>
    </head>

    <body>
        <script src="https://example.com/script.js"></script>
    </body>
</html>

I want to intercept these requests in my code so I can inspect the details of the request, and reroute them to a local cache. I use a subclass of WKNavigationDelegate, with an overridden DecidePolicy() method to intercept requests.

The problem is that DecidePolicy() does not get called for these two requests (for the CSS and JS files). DecidePolicy() only gets called when the user triggers a navigation action.

I have also tried using webViewConfiguration.SetUrlSchemeHandler() with an implementation of IWKUrlSchemeHandler, and replacing instances of "https://" with "customscheme://" in my HTML file, but the method StartUrlSchemeTask() does not get called.

How can I intercept requests for linked resources in an HTML file? Thanks

1

There are 1 answers

1
ColeX On

Try the following steps

  1. Register custom scheme with WKWebView .

  2. Convert file scheme to the custom scheme .

  3. Use LoadRequest instead of LoadHtmlString .

  4. Implement 2 methods of WKURLSchemeHandler protocol and handle 3 delegate methods of WKURLSchemeTask.

Refer to

https://stackoverflow.com/a/21959563/8187800

How to intercept a WKWebView request to detect which local resource files (css, js, png, ...) load together with a HTML file?.