1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

WKWebViewでtarget="_blank"(新しいタブで開く)について対応する

Posted at

課題

  • WKWebViewではtarget="_blank"が設定されているリンクをタップしたとき、デフォルトだと上手く遷移してくれません。

対応

  • 3つの対応が考えられます
  1. 新しいWebViewを作成して読み込む
  2. そのままのWebViewで読み込む
  3. ブラウザを立ち上げて逃がす

実装

1〜3の共通の実装について記載します。

実装クラスにWKUIDelegateを宣言する

final class Hoge: NSObject, ObservableObject, WKNavigationDelegate, WKUIDelegate {

WebViewにuiDelegateを設定する

webView.uiDelegate = self

web View(_: create Web View With: for: window Features:)を実装する

/// 新しいWebViewを作成する
func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
    if navigationAction.targetFrame == nil {
        // そのままのWebViewで読み込む
        // ブラウザを立ち上げて逃がす
    }
    return nil
}

そのままのWebViewで読み込む

func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
    if navigationAction.targetFrame == nil {
        // そのままのWebViewで読み込む
        webView.load(navigationAction.request)
    }
    return nil
}

ブラウザを立ち上げて逃がす

func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
    if navigationAction.targetFrame == nil {
        // ブラウザを立ち上げて逃がす
        openUrlInBrowser(navigationAction.request.url?.absoluteString ?? "")
    }
    return nil
}

/// デフォルトブラウザでURLを開く
private func openUrlInBrowser(_ urlString: String) {
    if let url = URL(string: urlString) {
        UIApplication.shared.open(url)
    }
}
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?