Load Javascript files through HTML file on WKWebView in iOS

為{幸葍}努か 提交于 2019-12-07 18:26:28

问题


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

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.

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

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.


回答1:


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.



来源:https://stackoverflow.com/questions/45371386/load-javascript-files-through-html-file-on-wkwebview-in-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!