如果應用程式使用 
WKWebView 顯示網頁內容,您可能需要考慮基於下列原因,最佳化點擊行為:
- 
WKWebView不支援分頁瀏覽。根據預設,嘗試開啟新分頁的廣告點擊不會有任何動作。
- 如果廣告點擊在同一個分頁中開啟,系統會重新載入該頁面。您可能想強制廣告點擊在 - WKWebView以外開啟,例如您代管 H5 遊戲,並想維持每個遊戲的狀態。
- 自動填入功能不支援 - WKWebView中的信用卡資訊。這可能會導致廣告主電子商務轉換次數減少,對網站內容的營利造成負面影響。
- Google 登入
不支援 WKWebView。
本指南提供建議步驟,協助您在保留網頁檢視內容的同時,最佳化行動版網頁檢視中的點擊行為。
必要條件
- 完成「設定網頁檢視畫面」指南。
導入作業
廣告連結的 href 目標屬性可設為 _blank、_top、_self 或 _parent。
廣告連結也可以包含 JavaScript 函式,例如 window.open(url, "_blank")。
下表說明這些連結在網頁檢視畫面中的行為。
| href目標屬性 | 預設的 WKWebView點擊行為 | 
|---|---|
| target="_blank" | 網頁檢視畫面未處理連結。 | 
| target="_top" | 在現有的網頁檢視畫面中重新載入連結。 | 
| target="_self" | 在現有的網頁檢視畫面中重新載入連結。 | 
| target="_parent" | 在現有的網頁檢視畫面中重新載入連結。 | 
| JavaScript 函式 | 預設的 WKWebView點擊行為 | 
| window.open(url, "_blank") | 網頁檢視畫面未處理連結。 | 
請按照下列步驟,在WKWebView執行個體中最佳化點擊行為:
- 在 - WKWebView執行個體上設定- WKUIDelegate。
- 在 - WKWebView執行個體上設定- WKNavigationDelegate。
- 判斷是否要最佳化點擊網址的行為。 - 檢查 - WKNavigationAction物件上的- navigationType屬性是否為您要最佳化的點擊類型。程式碼範例會檢查- .linkActivated,這只適用於點選含有- href屬性的連結。
- 檢查 - WKNavigationAction物件的- targetFrame屬性。如果傳回- nil,表示導覽目標是新視窗。由於- WKWebView無法處理該點擊動作,因此必須手動處理這些點擊動作。
 
- 決定要在外部瀏覽器中開啟網址, - 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? {
    // 3. Determine whether to optimize the behavior of the click URL.
    if didHandleClickBehavior(
        currentURL: webView.url,
        navigationAction: navigationAction) {
      print("URL opened in SFSafariViewController.")
    }
    return nil
  }
  // Implement the WKNavigationDelegate method.
  func webView(
      _ webView: WKWebView,
      decidePolicyFor navigationAction: WKNavigationAction,
      decisionHandler: @escaping (WKNavigationActionPolicy) -> Void)
  {
    // 3. Determine whether to optimize the behavior of the click URL.
    if didHandleClickBehavior(
        currentURL: webView.url,
        navigationAction: navigationAction) {
      return decisionHandler(.cancel)
    }
    decisionHandler(.allow)
  }
  // Implement a helper method to handle click behavior.
  func didHandleClickBehavior(
      currentURL: URL,
      navigationAction: WKNavigationAction) -> Bool {
    guard let targetURL = navigationAction.request.url else {
      return false
    }
    // Handle custom URL schemes such as itms-apps:// by attempting to
    // launch the corresponding application.
    if navigationAction.navigationType == .linkActivated {
      if let scheme = targetURL.scheme, !["http", "https"].contains(scheme) {
        UIApplication.shared.open(targetURL, options: [:], completionHandler: nil)
        return true
      }
    }
    guard let currentDomain = currentURL.host,
      let targetDomain = targetURL.host else {
      return false
    }
    // 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 == .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 {
      // 4. Open the URL in a SFSafariViewController.
      let safariViewController = SFSafariViewController(url: targetURL)
      present(safariViewController, animated: true)
      return true
    }
    return false
  }
}
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 {
  // 3. Determine whether to optimize the behavior of the click URL.
  if ([self didHandleClickBehaviorForCurrentURL: webView.URL
      navigationAction: navigationAction]) {
    NSLog(@"URL opened in SFSafariViewController.");
  }
  return nil;
}
// Implement the WKNavigationDelegate method.
- (void)webView:(WKWebView *)webView
    decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction
                    decisionHandler:
                        (void (^)(WKNavigationActionPolicy))decisionHandler {
  // 3. Determine whether to optimize the behavior of the click URL.
  if ([self didHandleClickBehaviorForCurrentURL: webView.URL
      navigationAction: navigationAction]) {
    decisionHandler(WKNavigationActionPolicyCancel);
    return;
  }
  decisionHandler(WKNavigationActionPolicyAllow);
}
// Implement a helper method to handle click behavior.
- (BOOL)didHandleClickBehaviorForCurrentURL:(NSURL *)currentURL
                    navigationAction:(WKNavigationAction *)navigationAction {
  NSURL *targetURL = navigationAction.request.URL;
  // Handle custom URL schemes such as itms-apps:// by attempting to
  // launch the corresponding application.
  if (navigationAction.navigationType == WKNavigationTypeLinkActivated) {
    NSString *scheme = targetURL.scheme;
    if (![scheme isEqualToString:@"http"] && ![scheme isEqualToString:@"https"]) {
      [UIApplication.sharedApplication openURL:targetURL options:@{} completionHandler:nil];
      return YES;
    }
  }
  NSString *currentDomain = currentURL.host;
  NSString *targetDomain = targetURL.host;
  if (!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:targetURL];
    [self presentViewController:safariViewController animated:YES
        completion:nil];
    return YES;
  }
  return NO;
}
測試網頁瀏覽
如要測試網頁導覽變更,請載入
https://google.github.io/webview-ads/test/#click-behavior-tests
到網頁檢視畫面。點選各種類型的連結,即可查看連結在應用程式中的行為。
建議您確認以下事項:
- 每個連結都會開啟預期網址。
- 返回應用程式時,測試頁面的計數器不會重設為零,以驗證頁面狀態是否保留。