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

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

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

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

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

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

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

  • מבצעים את ההוראות במדריך Set the web view (הגדרה של תצוגת האינטרנט).

הטמעה

אפשר להגדיר לקישורים של מודעות את מאפיין היעד 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 , צריך לפעול לפי השלבים הבאים:

  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? {
    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

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

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

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