I am trying to implement the functionality to open a new wkwebview in my viewcontroller when the user taps a link on a website that is configured to open in a new tab (URLs that have target=_blank). After some testing I've noticed that a new tab opens very inconsistently and the user just stays on the parent webview (new tab opens only 1 in 3 times). I'm using the following Objective-C implementation to achieve this:
RCT_EXPORT_METHOD(wkWebView:(NSURL *)nsurl) {
UIViewController *rootViewController = [[
[ UIApplication sharedApplication] keyWindow] rootViewController];
//WkWebview initialization
WKPreferences *wkPreferences = [[WKPreferences alloc] init];
wkPreferences.javaScriptCanOpenWindowsAutomatically = true;
WKWebViewConfiguration *theConfiguration = [[WKWebViewConfiguration alloc] init];
theConfiguration.preferences = wkPreferences;
dispatch_async(dispatch_get_main_queue(), ^{
self.controller = [[UIViewController alloc] init];
self.webView = [[WKWebView alloc] initWithFrame:rootViewController.view.frame configuration:theConfiguration];
self.webView.navigationDelegate = self;
self.webView.UIDelegate = self;
NSURLRequest *nsrequest=[NSURLRequest requestWithURL:nsurl];
[self.webView loadRequest:nsrequest];
self.controller.view = self.webView;
self.navigationController = [[UINavigationController alloc] initWithRootViewController:self.controller];
[self.navigationController setNavigationBarHidden:NO animated:YES];
[rootViewController presentViewController:self.navigationController animated:YES completion: nil];
});
}
- (nullable WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures {
self.popupWebView = [[WKWebView alloc] initWithFrame:self.webView.frame configuration:configuration];
self.popupWebView.UIDelegate = self;
self.popupWebView.navigationDelegate = self;
[self.webView addSubview:self.popupWebView];
return self.popupWebView;
}
Interface file:
@interface WkWebViewModule : NSObject <RCTBridgeModule, WKUIDelegate, WKNavigationDelegate>
@property (nonatomic) UIViewController *controller;
@property (nonatomic) UINavigationController *navigationController;
@property (nonatomic) WKWebView *webView;
@property (nonatomic) UINavigationItem *navItem;
@property (nonatomic) UINavigationBar *navbar;
@property (nonatomic) WKWebView *popupWebView;
@property (nonatomic) WKPreferences *wkPreferences;
@end