求助:实现AdMob广告点击后在App内WebView打开网页的方案
Hey there! I’ve worked through this exact requirement before, so let me break down how to get AdMob interstitial and banner ads to open in your app’s WebView instead of an external browser.
First, a critical note: Make sure you’re adhering to Google’s AdMob policies when modifying ad behavior. Opening ads in your app’s WebView is allowed as long as you don’t alter ad content, skip tracking events, or interfere with normal ad functionality.
Android Implementation
Step 1: Create a WebView Activity
First, build a dedicated activity to host your WebView. This will handle loading the ad URL and keeping navigation within the app.
Kotlin Code for AdWebViewActivity
import android.content.Intent import android.os.Bundle import android.webkit.WebResourceRequest import android.webkit.WebView import android.webkit.WebViewClient import androidx.appcompat.app.AppCompatActivity class AdWebViewActivity : AppCompatActivity() { private lateinit var webView: WebView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_ad_web_view) webView = findViewById(R.id.ad_web_view) configureWebView() // Load the ad URL passed from the main activity intent.getStringExtra("AD_TARGET_URL")?.let { url -> webView.loadUrl(url) } } private fun configureWebView() { webView.settings.apply { javaScriptEnabled = true // Required for most ads to render properly domStorageEnabled = true setSupportZoom(true) builtInZoomControls = true displayZoomControls = false } // Keep all navigation within the WebView instead of opening external apps webView.webViewClient = object : WebViewClient() { override fun shouldOverrideUrlLoading( view: WebView?, request: WebResourceRequest? ): Boolean { request?.url?.toString()?.let { view?.loadUrl(it) } return true } } } }
Layout File (activity_ad_web_view.xml)
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <WebView android:id="@+id/ad_web_view" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout>
Register the Activity in AndroidManifest.xml
Add this inside the <application> tag:
<activity android:name=".AdWebViewActivity" />
Step 2: Handle Interstitial Ad Clicks
Use FullScreenContentCallback to intercept interstitial ad clicks, retrieve the target URL, and launch your WebView activity.
import com.google.android.gms.ads.AdRequest import com.google.android.gms.ads.InterstitialAd import com.google.android.gms.ads.FullScreenContentCallback import com.google.android.gms.ads.AdError private fun loadInterstitialAd() { val interstitialAd = InterstitialAd(this) interstitialAd.adUnitId = "YOUR_INTERSTITIAL_AD_UNIT_ID" interstitialAd.fullScreenContentCallback = object : FullScreenContentCallback() { override fun onAdClicked() { super.onAdClicked() // Retrieve the ad's target URL from the response info interstitialAd.responseInfo?.loadedAdResponse?.ad?.contentUrl?.let { adUrl -> launchAdWebView(adUrl) } } override fun onAdFailedToShowFullScreenContent(adError: AdError) { // Handle ad show failure } } // Load the ad interstitialAd.loadAd(AdRequest.Builder().build()) } // Helper method to launch the WebView activity private fun launchAdWebView(url: String) { val intent = Intent(this, AdWebViewActivity::class.java) intent.putExtra("AD_TARGET_URL", url) startActivity(intent) }
Step 3: Handle Banner Ad Clicks
For banner ads, use BannerAdListener to intercept clicks and load the URL into your WebView.
import com.google.android.gms.ads.AdView import com.google.android.gms.ads.AdSize import com.google.android.gms.ads.AdListener private fun setupBannerAd() { val bannerAdView = AdView(this) bannerAdView.adUnitId = "YOUR_BANNER_AD_UNIT_ID" bannerAdView.adSize = AdSize.BANNER // Add the banner to your layout (replace with your container ID) val adContainer = findViewById<ViewGroup>(R.id.banner_container) adContainer.addView(bannerAdView) bannerAdView.adListener = object : AdListener() { override fun onAdClicked() { super.onAdClicked() // Retrieve the ad's target URL bannerAdView.responseInfo?.loadedAdResponse?.ad?.contentUrl?.let { adUrl -> launchAdWebView(adUrl) } } } // Load the banner ad bannerAdView.loadAd(AdRequest.Builder().build()) }
iOS Implementation
For iOS, use WKWebView and AdMob’s delegate methods to intercept ad clicks.
Step 1: Create a WebView ViewController
import UIKit import WebKit class AdWebViewController: UIViewController { private var webView: WKWebView! var adTargetUrl: String? override func viewDidLoad() { super.viewDidLoad() setupWebView() loadAdUrl() } private func setupWebView() { webView = WKWebView(frame: view.bounds) webView.navigationDelegate = self view.addSubview(webView) } private func loadAdUrl() { guard let urlString = adTargetUrl, let url = URL(string: urlString) else { return } let request = URLRequest(url: url) webView.load(request) } } extension AdWebViewController: WKNavigationDelegate { func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { // Keep navigation within the WebView decisionHandler(.allow) } }
Step 2: Handle Interstitial Ad Clicks
Use GADInterstitialDelegate to intercept clicks:
import GoogleMobileAds class YourViewController: UIViewController, GADInterstitialDelegate { private var interstitialAd: GADInterstitialAd? private func loadInterstitialAd() { GADInterstitialAd.load(withAdUnitID: "YOUR_INTERSTITIAL_AD_UNIT_ID", request: GADRequest()) { ad, error in guard let ad = ad else { return } self.interstitialAd = ad self.interstitialAd?.delegate = self } } // Delegate method for ad click func interstitialAdDidRecordClick(_ ad: GADInterstitialAd) { guard let adUrl = ad.responseInfo?.loadedAdResponse?.ad.contentURL else { return } launchAdWebView(url: adUrl.absoluteString) } private func launchAdWebView(url: String) { let webVC = AdWebViewController() webVC.adTargetUrl = url present(webVC, animated: true) } }
Step 3: Handle Banner Ad Clicks
Use GADBannerViewDelegate for banner ads:
import GoogleMobileAds class YourViewController: UIViewController, GADBannerViewDelegate { private var bannerView: GADBannerView! private func setupBannerAd() { bannerView = GADBannerView(adSize: GADAdSizeBanner) bannerView.adUnitID = "YOUR_BANNER_AD_UNIT_ID" bannerView.rootViewController = self bannerView.delegate = self // Add banner to your view (adjust constraints as needed) view.addSubview(bannerView) bannerView.load(GADRequest()) } // Delegate method for ad click func bannerViewDidRecordClick(_ bannerView: GADBannerView) { guard let adUrl = bannerView.responseInfo?.loadedAdResponse?.ad.contentURL else { return } launchAdWebView(url: adUrl.absoluteString) } }
Important Notes
- AdMob Policies: Ensure you don’t modify ad content or skip any tracking events. The above methods preserve AdMob’s click tracking since we’re using the official delegate callbacks.
- URL Retrieval: The
contentUrlproperty may not always be available (e.g., for some native ads or custom ads), but it works reliably for standard interstitial and banner ads. - WebView Configuration: Always enable JavaScript and DOM storage to ensure ads render correctly, as most modern ads rely on these features.
内容的提问来源于stack exchange,提问作者AAhmad Blal

