WKWebView Crashed when window.alert(), Part II

As previous post said, we face WKWebView would crash at window.alert() and solution was only to present UIAlertController if and only if UIViewController with embedded WKWebView is visible.
And now our lead iOS engineer found another use case would occur the same crash; when WKWebView already presented a viewcontroller or alert-controller, and it try to present another viewcontroller before previous one dismissed.

It’s not enought to present alert dialog only when WKWebView is visible. If there is already a presented viewcontroller, WKWebView still crashes when it tries to present one more alter dialog.

  • Refined Solution:
  1. Present your UIAlertController if and only if UIViewController with WKWebView is visible and no other presented viewcontroller
  2. If not visible, execute completionHandler directly and return.

Here is example of implementation:

(void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler 
{
UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"My Alert" message:@"This is an alert." preferredStyle:UIAlertControllerStyleAlert];

UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) { completionHandler(); }];
[alert addAction:defaultAction];

if (self.isVisible && !self.presentedViewController) {
[self presentViewController:alert animated:YES completion:nil];
} else {
completionHandler();
}

}