אופטימיזציה של התנהגות הקליקים של WKWebView

אם האפליקציה שלכם משתמשת ב-WKWebView כדי להציג תוכן אינטרנט, כדאי לשקול אופטימיזציה של התנהגות הקליקים מהסיבות הבאות:

  • WKWebView לא תומך בגלישה בכרטיסיות. כברירת מחדל, קליקים על מודעות שמנסים לפתוח כרטיסייה חדשה לא עושים כלום.

  • קליקים על מודעות שנפתחות באותה כרטיסייה גורמים לטעינה מחדש של הדף. לפעמים כדאי להגדיר שלחיצה על מודעה תפתח אותה מחוץ ל-WKWebView, למשל אם אתם מארחים משחקי H5 ורוצים לשמור על הסטטוס של כל משחק.

  • המילוי האוטומטי לא תומך בפרטי כרטיס אשראי ב-WKWebView. הדבר עלול להוביל לירידה במספר ההמרות של מסחר אלקטרוני למפרסמים, ולהשפיע לרעה על המונטיזציה של תוכן האינטרנט.

במדריך הזה מפורטים שלבים מומלצים לאופטימיזציה של התנהגות הלחיצה בתצוגות אינטרנט בנייד, תוך שמירה על התוכן של תצוגת האינטרנט.

דרישות מוקדמות

הטמעה

ערך המאפיין target של קישורי מודעות יכול להיות href, _blank, _top, _self או _parent. ב-Ad Manager אפשר לשלוט במאפיין היעד ולהגדיר אותו כ-_blank או כ-_top על ידי הגדרת המודעות כך שייפתחו בכרטיסייה או בחלון חדשים. קישורים למודעות יכולים להכיל גם פונקציות JavaScript כמו window.open(url, "_blank").

בטבלה הבאה מתואר אופן הפעולה של כל אחד מהקישורים האלה בתצוגת אינטרנט.

href מאפיין יעד התנהגות ברירת המחדל של קליקים על WKWebView
target="_blank" הקישור לא מטופל על ידי תצוגת האינטרנט.
target="_top" טעינה מחדש של הקישור בתצוגת האינטרנט הקיימת.
target="_self" טעינה מחדש של הקישור בתצוגת האינטרנט הקיימת.
target="_parent" טעינה מחדש של הקישור בתצוגת האינטרנט הקיימת.
פונקציה ב-JavaScript התנהגות ברירת המחדל של קליקים על WKWebView
window.open(url, "_blank") הקישור לא מטופל על ידי תצוגת האינטרנט.

כדי לבצע אופטימיזציה של התנהגות הקליקים במופע WKWebView:

  1. מגדירים את WKUIDelegate במופע WKWebView.

  2. מגדירים את WKNavigationDelegate במופע WKWebView.

  3. מחליטים אם לבצע אופטימיזציה של ההתנהגות של כתובת היעד של הקליק.

    • בודקים אם המאפיין navigationType באובייקט WKNavigationAction הוא סוג הקליק שרוצים לבצע לו אופטימיזציה. בדוגמת הקוד מתבצעת בדיקה של .linkActivated, שרלוונטית רק לקליקים על קישור עם מאפיין href.

    • בודקים את המאפיין targetFrame באובייקט WKNavigationAction. אם הפונקציה מחזירה nil, המשמעות היא שיעד הניווט הוא חלון חדש. מכיוון ש-WKWebView לא יכול לטפל בקליק הזה, צריך לטפל בקליקים האלה באופן ידני.

  4. לבחור אם לפתוח את כתובת ה-URL בדפדפן חיצוני, SFSafariViewController, או בתצוגת האינטרנט הקיימת. בקטע הקוד מוצג איך לפתוח כתובות URL שמובילות מחוץ לאתר באמצעות הצגת 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

לתצוגת האינטרנט. כדאי ללחוץ על כל אחד מסוגי הקישורים כדי לראות איך הם מתנהגים באפליקציה.

הנה כמה דברים שכדאי לבדוק:

  • כל קישור פותח את כתובת ה-URL הרצויה.
  • כשחוזרים לאפליקציה, המונה בדף הבדיקה לא מתאפס לאפס כדי לאמת שהמצב של הדף נשמר.