最佳化 WKWebView 點擊行為

如果您的應用程式使用 WKWebView 顯示網頁內容,您可能會考慮基於下列原因,改善點擊行為:

  • WKWebView 不支援分頁瀏覽。根據預設,嘗試開啟新分頁的廣告點擊不會執行任何操作。

  • 在同一個分頁中開啟的廣告點擊會重新載入網頁。您可能需要強制廣告點擊在 WKWebView 外開啟,例如如果您代管 H5 遊戲,且想維持每個遊戲的狀態。

  • 自動填入功能不支援 WKWebView 中的信用卡資訊。這可能會導致廣告客戶的電子商務轉換次數減少,進而影響網站內容的營利情形。

本指南提供最佳化步驟,協助您在保留網頁檢視畫面內容的同時,改善行動版網頁檢視畫面的點擊行為。

必要條件

實作

廣告連結的 href 目標屬性可設為 _blank_top_self_parent。您可以使用 Ad Manager 將廣告設為在新分頁或視窗中開啟,藉此控制目標屬性為 _blank_top。廣告連結也可以包含 window.open(url, "_blank") 等 JavaScript 函式。

下表說明這些連結在網頁檢視畫面中的行為。

href 目標屬性 預設 WKWebView 點擊行為
target="_blank" 網頁檢視器「未處理」連結。
target="_top" 重新載入現有網頁檢視畫面中的連結。
target="_self" 重新載入現有網頁檢視畫面中的連結。
target="_parent" 重新載入現有網頁檢視畫面中的連結。
JavaScript 函式 預設 WKWebView 點擊行為
window.open(url, "_blank") 網頁檢視器「未處理」連結。

請按照下列步驟,在 WKWebView 例項中改善點擊行為:

  1. WKWebView 執行個體上設定 WKUIDelegate

  2. WKWebView 執行個體上設定 WKNavigationDelegate

  3. 決定是否要最佳化點擊網址的行為。

    • 請檢查 WKNavigationAction 物件上的 navigationType 屬性,是否是您要最佳化的點擊類型。程式碼範例會檢查 .linkActivated,但只適用於點選含有 href 屬性的連結。

    • 檢查 WKNavigationAction 物件的 targetFrame 屬性。如果傳回 nil,表示導覽的目標是新視窗。由於 WKWebView 無法處理點擊,因此必須手動處理這些點擊。

  4. 決定是否要在外部瀏覽器、SFSafariViewController 或現有的網頁檢視畫面中開啟網址。程式碼片段說明如何透過呈現 SFSafariViewController,開啟從網站離開的網址。

程式碼範例

下列程式碼片段說明如何最佳化網頁檢視畫面的點擊行為。舉例來說,它會檢查目前網域是否與目標網域不同。這只是其中一種方法,因為您使用的條件可能會有所不同。

Swift

import GoogleMobileAds
import SafariServices
import WebKit

class ViewController: UIViewController, WKNavigationDelegate, WKUIDelegate {

  override func viewDidLoad() {
    super.viewDidLoad()

    // ... Register the WKWebView.

    // 1. Set the WKUIDelegate on your WKWebView instance.
    webView.uiDelegate = self;
    // 2. Set the WKNavigationDelegate on your WKWebView instance.
    webView.navigationDelegate = self
  }

  // Implement the WKUIDelegate method.
  func webView(
      _ webView: WKWebView,
      createWebViewWith configuration: WKWebViewConfiguration,
      for navigationAction: WKNavigationAction,
      windowFeatures: WKWindowFeatures) -> WKWebView? {
    guard let url = navigationAction.request.url,
        let currentDomain = webView.url?.host,
        let targetDomain = url.host else { return nil }

    // 3. Determine whether to optimize the behavior of the click URL.
    if didHandleClickBehavior(
        url: url,
        currentDomain: currentDomain,
        targetDomain: targetDomain,
        navigationAction: navigationAction) {
      print("URL opened in SFSafariViewController.")
    }

    return nil
  }

  // Implement the WKNavigationDelegate method.
  func webView(
      _ webView: WKWebView,
      decidePolicyFor navigationAction: WKNavigationAction,
      decisionHandler: @escaping (WKNavigationActionPolicy) -> Void)
  {
    guard let url = navigationAction.request.url,
        let currentDomain = webView.url?.host,
        let targetDomain = url.host else { return decisionHandler(.cancel) }

    // 3. Determine whether to optimize the behavior of the click URL.
    if didHandleClickBehavior(
        url: url,
        currentDomain: currentDomain,
        targetDomain: targetDomain,
        navigationAction: navigationAction) {
      return decisionHandler(.cancel)
    }

    decisionHandler(.allow)
  }

  // Implement a helper method to handle click behavior.
  func didHandleClickBehavior(
      url: URL,
      currentDomain: String,
      targetDomain: String,
      navigationAction: WKNavigationAction) -> Bool {
    // Check if the navigationType is a link with an href attribute or
    // if the target of the navigation is a new window.
    guard navigationAction.navigationType == .linkActivated ||
      navigationAction.targetFrame == nil,
      // If the current domain does not equal the target domain,
      // the assumption is the user is navigating away from the site.
      currentDomain != targetDomain else { return false }

    // 4.  Open the URL in a SFSafariViewController.
    let safariViewController = SFSafariViewController(url: url)
    present(safariViewController, animated: true)
    return true
  }
}

Objective-C

@import GoogleMobileAds;
@import SafariServices;
@import WebKit;

@interface ViewController () <WKNavigationDelegate, WKUIDelegate>

@property(nonatomic, strong) WKWebView *webView;

@end

@implementation ViewController

- (void)viewDidLoad {
  [super viewDidLoad];

  // ... Register the WKWebView.

  // 1. Set the WKUIDelegate on your WKWebView instance.
  self.webView.uiDelegate = self;
  // 2. Set the WKNavigationDelegate on your WKWebView instance.
  self.webView.navigationDelegate = self;
}

// Implement the WKUIDelegate method.
- (WKWebView *)webView:(WKWebView *)webView
  createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration
             forNavigationAction:(WKNavigationAction *)navigationAction
                  windowFeatures:(WKWindowFeatures *)windowFeatures {
  NSURL *url = navigationAction.request.URL;
  NSString *currentDomain = webView.URL.host;
  NSString *targetDomain = navigationAction.request.URL.host;

  // 3. Determine whether to optimize the behavior of the click URL.
  if ([self didHandleClickBehaviorForURL: url
      currentDomain: currentDomain
      targetDomain: targetDomain
      navigationAction: navigationAction]) {
    NSLog(@"URL opened in SFSafariViewController.");
  }

  return nil;
}

// Implement the WKNavigationDelegate method.
- (void)webView:(WKWebView *)webView
    decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction
                    decisionHandler:
                        (void (^)(WKNavigationActionPolicy))decisionHandler {
  NSURL *url = navigationAction.request.URL;
  NSString *currentDomain = webView.URL.host;
  NSString *targetDomain = navigationAction.request.URL.host;

  // 3. Determine whether to optimize the behavior of the click URL.
  if ([self didHandleClickBehaviorForURL: url
      currentDomain: currentDomain
      targetDomain: targetDomain
      navigationAction: navigationAction]) {

    decisionHandler(WKNavigationActionPolicyCancel);
    return;
  }

  decisionHandler(WKNavigationActionPolicyAllow);
}

// Implement a helper method to handle click behavior.
- (BOOL)didHandleClickBehaviorForURL:(NSURL *)url
                       currentDomain:(NSString *)currentDomain
                        targetDomain:(NSString *)targetDomain
                    navigationAction:(WKNavigationAction *)navigationAction {
  if (!url || !currentDomain || !targetDomain) {
    return NO;
  }

  // Check if the navigationType is a link with an href attribute or
  // if the target of the navigation is a new window.
  if ((navigationAction.navigationType == WKNavigationTypeLinkActivated
      || !navigationAction.targetFrame)
      // If the current domain does not equal the target domain,
      // the assumption is the user is navigating away from the site.
      && ![currentDomain isEqualToString: targetDomain]) {

     // 4.  Open the URL in a SFSafariViewController.
    SFSafariViewController *safariViewController =
        [[SFSafariViewController alloc] initWithURL:url];
    [self presentViewController:safariViewController animated:YES
        completion:nil];
    return YES;
  }

  return NO;
}

測試網頁導覽

如要測試網頁導覽變更,請載入

https://webview-api-for-ads-test.glitch.me#click-behavior-tests

至網頁檢視畫面。點選各個不同連結類型,查看這些連結在應用程式中的運作方式。

建議您確認以下事項:

  • 每個連結都會開啟指定的網址。
  • 返回應用程式時,測試頁面的計數器不會重設為零,以驗證網頁狀態是否已保留。