Saturday, May 5, 2018

ios uiwebview xmlhttprequest fails to load local data file from local html page

When local html file is loaded into iOS UIWebView, as long as content security policy does not have limitation, then the javascript code in local html page can use xmlhttprequest to get data from remote server, for example, http://www.odata.com.

However, on the same html page, using xmlhttprequest to load file from local file system using the relative path will fail. The xmlhttprequest will return status 0 in onload callback method (readystate 4). This is strange, as usually the application should always trust the local file system than external web server.

Note even if the status is set to 0, the xmlhttprequest.responseText field already contains the file content. So one workaround is checking the responseText field, and if it is not "", then handle the response as if the status code is 200. A sample code is shown below

  
            var x = new XMLHttpRequest();
           
            x.addEventListener('load', function(e) {
                if (x.status === 200 || x.responseText != "" ) {
                   //handle success
                } else {
                    //handle error
                }
            });
            x.addEventListener('error', function(e) {
                //handle error
            });
            x.open('GET', url);
            try {
                x.send();
            } catch (b) {
               //handle error
            }
        }


No comments:

Post a Comment