14

You can disable Javascript in both mobile Safari and Cocoa's WebView but I can see no means of doing so in UIWebView.

Am I correct?

I ask in relation to this question regarding obtaining the title of page displayed in an UIWebView using Javascript. I had worried that it would fail if Javascript was disabled but it appears the API does not allow the disabling of Javascript.

If Javascript cannot be deactivated UIWebView,that renders my previous question moot.

1

2 Answers 2

13

There is a way! Using the Content Security Policy which is partially supported in iOS 5.1 and up, and a custom header:

X-WebKit-CSP: script-src none;

You can tell the UIWebKit to not allow javascript on the page entirely. (or selectively only allow script from a specific domain, more information in the spec.

To do this from a server you control, you'll have to modify the response headers for the page to include the X-WebKit-CSP header... To do it from pages that are local (plain text or HTML data on device), you'll have to define and register a custom NSURLProtocol for loading your page, and send the header in your crafted NSHTTPURLResponse:

NSDictionary *headers = [NSDictionary dictionaryWithObjectsAndKeys:
                         @"script-src none",@"X-WebKit-CSP",
                         @"text/html",@"Content-type",
                         encoding,@"Content-encoding",
                         nil];
NSHTTPURLResponse *urlResponse = [[NSHTTPURLResponse alloc] initWithURL:self.request.URL
                                                         statusCode:200
                                                        HTTPVersion:@"1.1"
                                                       headerFields:headers];
[self.client URLProtocol:self didReceiveResponse:urlResponse cacheStoragePolicy:NSURLCacheStorageAllowedInMemoryOnly];
4
  • Sadly this one doesn't work with iframes. <iframe src="data:text/html,<script>alert(1)</script>"> Jun 11, 2014 at 21:33
  • 1
    @AlexanderSmirnov -- If you user your custom NSURLProtocol handler to handle iframes as well -- You'll have to catch all outbound calls (use the delegate callbacks in UIWebView to make sure that it swaps your schema for http or https whenever a URL call is made)
    – BadPirate
    Jun 12, 2014 at 5:30
  • @BadPirate Could you provide me more codes. I don't understand how prevent XSS when load an html string with loadHtmlString:baseURL:. Thanks
    – Giorgio
    Feb 26, 2016 at 15:54
  • 2
    There is a way to do this if you are using new WKWebView instead of UIWebView. Which is answered here. stackoverflow.com/a/34404676/1239426
    – MadNik
    Mar 7, 2016 at 9:43
9

There is no public API to disable Javascript. So it is fairly safe to assume that it won't be disabled.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.