1

I am very new so bear with me. I had an youtube video embed in a WKWebView playing fine on macOS in Objective-C. At first, none of the standard youtube links on the video (channel, recommended videos, etc) would load. I think this was because youtube uses _blank target links. The following code fixed it so any video links will now open in the WKWebView.

- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures
{
    NSLog(@"createWebViewWithConfiguration %@ %@", navigationAction, windowFeatures);
    if (!navigationAction.targetFrame.isMainFrame) {
        [(WKWebView *)_webView loadRequest:navigationAction.request];
    }
    return nil;
}

However, I would like these links to open in the macOS browser, and not WKWebview. Lot's of swift examples on iOS, but can't seem to get links to open from WKWebView in safari.

I have tried:

if (!navigationAction.targetFrame.isMainFrame) {
     [[NSApplication sharedApplication] openURL:[navigationAction.request URL]];
}

But doesn't work on macOS

BinDev
  • 191
  • 13
  • 1
    Does this answer your question? [Open url in safari through cocoa app](https://stackoverflow.com/questions/21745586/open-url-in-safari-through-cocoa-app) – Willeke Aug 07 '20 at 00:41

2 Answers2

2

This is what eventually worked for me. Seems to open any url (including javascript type popovers used in YouTube) in Safari instead of opening them in WKWebView (or not opening them at all).

- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures
{
    NSLog(@"createWebViewWithConfiguration %@ %@", navigationAction, windowFeatures);
    if (!navigationAction.targetFrame.isMainFrame) {
       [[NSWorkspace sharedWorkspace] openURL:[navigationAction.request URL]];
    }
    return nil;
}
BinDev
  • 191
  • 13
0

Not 100% sure but I've seen this circulated online for opening URLs on Mac. Give it a try.

[[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://stackoverflow.com"]];
  • 1
    It definately set me in the right direction. Solution was to use NSWorkspace over NS Application, but not with the URLWithString. Thank you for pointing me in the right direction though. – BinDev Aug 12 '20 at 14:39