Ajax calls from local Html file works in UIWebView but not in WKWebView

user_2788user_2788 CHMember ✭✭

Hi,

I am trying to make an AJAX request to a remote server from a local html file loaded in a web view.
It works perfectly in a UIWebView but it does not work in a WKWebView.

The local html file is stored in the application and simply contains:

<html>
<body>
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<h1>Test AJAX</h1>
<br />
<button type="button" onclick="javascript: TestAjax();">Test AJAX</button>
<br />
<p id="result">Result:</p>
<script type="text/javascript">

    function TestAjax(data) {
        $.ajax({
            url: "https://www.google.com",
            success: function (result) {
                $("#result").html(result);
            },
            error: function (jqXHR, exception) {
                $("#result").html('An error occured: ' + jqXHR.responseText + exception);
            },
        });
    }
&lt;/script&gt;

</body>
</html>

This code works, the html page is displayed and when I click on the button the content of www.google.fr is correctly loaded:

[...]
var webView = new UIWebView();
string fileName = "Assets/index.html";
var url = new NSUrl(fileName, false);
webView.LoadRequest(new NSUrlRequest(url));
[...]

The same code using a WKWebView displays the html page but when I click on the button an undefined error occurs:

[...]
var webView = new WKWebView(Frame, new WKWebViewConfiguration());
string fileName = "Assets/index.html";
var url = new NSUrl(fileName, false);
webView.LoadRequest(new NSUrlRequest(url));
[..]

Can anybody help me ? I have looked into disabling CORS and things like that but nothing worked.

Thank you.

Answers

  • nabendumisranabendumisra USMember

    Hi,

    This bug has been fixed for WKWebView on the IOS side (Objective C Code)

    https://bugs.webkit.org/show_bug.cgi?id=167131

    Can anybody from the Xamarin team help to incorporate this fix
    on the WebKit.WKWebView .NET API interfacing the aforementioned

  • DavaaronDavaaron Member ✭✭

    Hey,

    I know this thread is dead. Just wanted to point out that I currently have the exact same problem.
    Requests with xhr are made and I get the error "cross origin requests are only supported for http".

    Within the WkWebviewRenderer, I added
    Configuration.Preferences.SetValueForKey(NSObject.FromObject(true), new NSString("allowFileAccessFromFileURLs")); Configuration.Preferences.SetValueForKey(NSObject.FromObject(true), new NSString("allowUniversalAccessFromFileURLs"));

    but the errors are still coming up. It's saying something like:
    "xmlhttprequests cannot load. cross origin requests are only supported for http"

Sign In or Register to comment.