Search code examples
javascriptiosobjective-cuiwebview

Can I disable JS in a UIWebView? (Objective C)


I'm writing a simple RSS reader for iOS using Xcode 8 and building for iOS 10.0.

I allow the user to save webpages for offline reading; however, when there is no internet connection, local HTML files take a long time to load as the UIWebView I'm loading them with tries to resolve external assets like images etc (or at least, that's what I think it's doing). I figured disabling JS when an internet connection is not present would solve this problem, but I don't know how to do that and I haven't found much information on the matter.

tl,dr: is there a way to disable javascript in a UIWebView?

Thank you


Solution

  • If you are building for iOS 10.0 you should use WKWebView instead. It has support for disabling javascript, and is also the recommended component to use.

    First create the preferences object. You need to set this up before the web view is created.

    WKPreferences *preferences = [[WKPreferences alloc] init];
    preferences.javaScriptEnabled = NO; // Here its set
    
    // Other things you might want to disable
    preferences.javaScriptCanOpenWindowsAutomatically = NO;
    

    Then create the configuration object which holds the preferences.

    WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
    configuration.preferences = preferences;
    

    Then create your web view.

    WKWebView *webView = [[WKWebView alloc] initWithFrame:frame configuration:configuration];
    

    Read more about WKWebView here