LoginSignup
0
0

More than 3 years have passed since last update.

WKWebView 内の URL テキストがリンクにならない

Posted at

やったこと

  • Xcode 11.3
  • 今更ながら、UIWebView から WkWebView への置き換え作業をやっていた
  • DataDetector に Link を設定
WKWebViewConfiguration *webConfig = [[WKWebViewConfiguration alloc] init];
webConfig.dataDetectorTypes = WKDataDetectorTypeLink;
webView = [[WKWebView alloc] initWithFrame:self.bounds configuration:webConfig];
[self addSubview:webView];

問題発生

  • UIWebView ではちゃんとリンクになっていた テキスト http://hogefuga.moge の部分がリンクにならない

原因

  • どうやら原因は css 内のこいつ
-webkit-user-select: none;
  • こいつを消すと URL のテキストがちゃんとリンクになる
  • こいつが何をしているかというと、WebView 内のロングタップで選択状態になるのを抑止している
    • Webビュー内のコンテンツをコピーさせたくないので設定していた
  • WKWebView では選択させないようにする = リンクもさせないということらしい
  • これも一緒(それはそう)
WKUserScript *disableSelectionScript = [[WKUserScript alloc] initWithSource:@"document.documentElement.style.webkitUserSelect='none';" injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:NO];
WKUserContentController *webController = [[WKUserContentController alloc] init];
[webController addUserScript:disableSelectionScript];
WKWebViewConfiguration *webConfig = [[WKWebViewConfiguration alloc] init];
webConfig.userContentController = webController;
webView = [[WKWebView alloc] initWithFrame:self.bounds configuration:webConfig];
[self addSubview:webView];

解決方法

  • 上記 CSS の設定を削除して canPerformAction の return を NO にした上で選択状態になることを是とする(かっこ悪い)
  • URL 部分を <a> タグでちゃんとリンクにする

未検証

  • 多分 Swift でも一緒
  • 多分 dataDetectorTypes に設定する値が変わっても一緒
0
0
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
0
0