整合廣告適用的 WebView API

使用廣告專用的網頁瀏覽 API,WKWebView 中的標記就能存取應用程式信號,有助內容發布商提升營利成效,同時保護廣告主不受垃圾內容干擾。

運作方式

只有在回應下列任一項目觸發的廣告事件時,才會與 Google Mobile Ads SDK 通訊:

SDK 會將訊息處理常式加到已註冊的 WKWebView,藉此監聽這些廣告事件。詳細運作方式請見測試網頁的原始碼

必要條件

  • Google Mobile Ads SDK 9.6.0 以上版本。
  • 使用下列鍵和字串值更新 Info.plist 檔案。這樣做會略過 Google Mobile Ads SDK 對 GADApplicationIdentifier 值的檢查,適用於在網頁檢視區塊以外導入廣告的開發人員。如果遺漏這個步驟且未提供 GADApplicationIdentifier,Google Mobile Ads SDK 會在應用程式啟動時擲回 GADInvalidInitializationException

    <!-- Indicate Google Mobile Ads SDK usage is only for web view APIs for ads -->
    <key>GADIntegrationManager</key>
    <string>webview</string>
    

註冊網頁檢視畫面

在主要執行緒上呼叫 register(_:),與每個 WKWebView 執行個體中的 AdSense 程式碼或 Google 發布商廣告代碼,建立 JavaScript 處理常式連線。這項操作應盡早完成,例如在檢視畫面控制器的 viewDidLoad 方法中執行。

Swift

import WebKit

class ViewController: UIViewController {

  var webView: WKWebView!

  override func viewDidLoad() {
    super.viewDidLoad()

    // Initialize a WKWebViewConfiguration object.
    let webViewConfiguration = WKWebViewConfiguration()
    // Let HTML videos with a "playsinline" attribute play inline.
    webViewConfiguration.allowsInlineMediaPlayback = true
    // Let HTML videos with an "autoplay" attribute play automatically.
    webViewConfiguration.mediaTypesRequiringUserActionForPlayback = []

    // Initialize the WKWebView with your WKWebViewConfiguration object.
    webView = WKWebView(frame: view.frame, configuration: webViewConfiguration)
    view.addSubview(webView)

    // Register the web view.
    MobileAds.shared.register(webView)
  }
}

Objective-C

@import WebKit;

#import "ViewController.h"

@interface ViewController ()

@property(nonatomic, strong) WKWebView *webView;

@end

@implementation ViewController

- (void)viewDidLoad {
  [super viewDidLoad];

  // Initialize a WKWebViewConfiguration object.
  WKWebViewConfiguration *webViewConfiguration = [[WKWebViewConfiguration alloc] init];
  // Let HTML videos with a "playsinline" attribute play inline.
  webViewConfiguration.allowsInlineMediaPlayback = YES;
  // Let HTML videos with an "autoplay" attribute play automatically.
  webViewConfiguration.mediaTypesRequiringUserActionForPlayback = WKAudiovisualMediaTypeNone;

  // Initialize the WKWebView with your WKWebViewConfiguration object.
  self.webView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:webViewConfiguration];
  [self.view addSubview:self.webView];

  // Register the web view.
  [GADMobileAds.sharedInstance registerWebView:self.webView];
}

測試整合功能

套用自己的網址前,建議先載入下列網址測試整合結果:

https://google.github.io/webview-ads/test/#api-for-ads-tests

只要符合下列條件,測試網址就會顯示綠色狀態列,代表整合成功:

  • WKWebView 已連結至 Google Mobile Ads SDK

後續步驟

  • WKWebView 中收集同意聲明。對於在行動應用程式執行情境中收集到的同意聲明,廣告專用的網頁瀏覽 API 不會使用 IAB 資訊公開和同意聲明架構第 2 版IAB CCPA 法規遵循架構,將這類同意聲明傳播至網頁瀏覽中的標記。如果您同時擁有 WKWebView 及相應的營利網路內容,且想要導入單一同意聲明流程,可與同意聲明管理平台合作,在 WKWebView 執行情境中收集同意聲明。