Home > Enterprise >  How to get the URL of current wkwebview that was opened in a new tab?
How to get the URL of current wkwebview that was opened in a new tab?

Time:09-04

I have a WkWebview that opens a child WkWebview in a new tab. I am trying to display the URL of the current webview to the user at the top in the navigation bar. I'm able to achieve this using the webView.URL property for the parent webview, but this same property returns a blank string when used for the child webview. I've also tried using the navigationAction.request.URL as an alternative for the child webview, but that also returns an empty string. The child webview opens flawlessly and I don't see any other issues in it other than the URL thing. How can I get the current URL of the child webview?

Code for creating a child webview that opens in a new tab:

    - (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];
    NSLog( @"Pop up webview navigationAction URL: '%@'", navigationAction.request.URL.absoluteString );
    self.controller.navigationItem.title = navigationAction.request.URL.absoluteString;
    return self.popupWebView;
}

Edit: Adding the interface to which "self" is referring to in the above code:

NS_ASSUME_NONNULL_BEGIN

@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

NS_ASSUME_NONNULL_END

CodePudding user response:

Not 100% sure, but you might have to get the URL AFTER the page has loaded using the delegate self.popupWebView.UIDelegate because at the point you are trying to get the URL, the WkWebView has been created, but has no content ?

  • Related