Ganesh G
Ganesh G

Reputation: 2061

Load Javascript files through HTML file on WKWebView in iOS

I have a requirement of loading Javascript files through HTML file. I have structured files in order shown in below screenshot.

enter image description here

HTML head tag contains the Javascript files to call as below:

<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<script type="text/javascript" src="AjaxCapturer.js"></script>
<script type="text/javascript" src="authenticate.js"></script>
</head>

So I have been using UIWebView to load the page and its loading properly as shown in below screenshot.

enter image description here

Now if I run same thing using WKWebView then the page is keep on loading as shown in below screenshot.

enter image description here

Javascript files are firing (added alert) but page does not load in WKWebView. Below is my code logic:

-(void)loadWebVW{

    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    WKPreferences *pref = [[WKPreferences alloc] init];
    pref.javaScriptEnabled = YES;
    pref.javaScriptCanOpenWindowsAutomatically = YES;
    config.preferences = pref;

    CGRect vwFrame = CGRectMake(10, 80, 300, 480);
    WKWebView *webVW = [[WKWebView alloc] initWithFrame:vwFrame configuration:config];
    [self.view addSubview:webVW];
    webVW.navigationDelegate = self;
    webVW.UIDelegate = self;

    NSString *htmlPath = [[NSBundle mainBundle] pathForResource:@"offline_Forms"
                                                         ofType:@"html"];
    NSString *html = [NSString stringWithContentsOfFile:htmlPath
                                               encoding:NSUTF8StringEncoding
                                                  error:nil];
    NSURL *baseUrl = [NSURL fileURLWithPath:
                      [NSString stringWithFormat:@"%@/JavaScript",
                       [[NSBundle mainBundle] bundlePath]]];
    [webVW loadHTMLString:html baseURL:baseUrl];

    //or//

    // [webVW loadRequest:[NSMutableURLRequest requestWithURL:[NSURL URLWithString:htmlPath]]];

}

Do we need to add any additional stuff to load it in WKWebView. Please help on this. Thanks in advance.

Upvotes: 2

Views: 3545

Answers (1)

Ganesh G
Ganesh G

Reputation: 2061

I found that it is a known issue in iOS 10.3 and fixed later in iOS 10.3.2, see link from Apple developer forum for more information. Sometimes I feel that the same issue being existed in Simulator but works fine in physical devices. So make sure every time you verify WKWebView functionality in physical device.

Upvotes: 1

Related Questions