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

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

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

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

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

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

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

הטמעה

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

    • בודקים אם הנכס 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://webview-api-for-ads-test.glitch.me#click-behavior-tests

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

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

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