我正在使用下面显示的代码在WebView
中加载Google广告。当我点击广告时,链接会在WebView
本身打开。
如何在Android浏览器中打开它?
我尝试使用WebViewClient
设置shouldOverrideUrlLoading
但是当我点击广告时,系统不会调用该方法。
当我在我的电脑上运行Chrome
中的javascript代码时,它会在新窗口中正确打开。
我错过了什么?
修改
我尝试使用onLoadResource
通过收听包含googleads.g.doubleclick.net
的网址来检测点击事件,但问题是在广告加载期间,即在点击之前加载了此类网址。
我如何模仿Chrome的行为,在没有任何黑客攻击的情况下在新窗口中打开网址?
ad.html
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
var googletag = googletag || {};
googletag.cmd = googletag.cmd || [];
(function() {
var gads = document.createElement('script');
gads.async = true;
gads.type = 'text/javascript';
var useSSL = 'https:' == document.location.protocol;
gads.src = (useSSL ? 'https:' : 'http:') +
'//www.googletagservices.com/tag/js/gpt.js';
var node = document.getElementsByTagName('script')[0];
node.parentNode.insertBefore(gads, node);
})();
</script>
<script type='text/javascript'>
googletag.cmd.push(function() {
googletag.defineSlot('/123456789/xxxx', [320, 50], 'div-gpt-ad-123456789-0').addService(googletag.pubads());
googletag.pubads().enableSingleRequest();
googletag.enableServices();
});
</script>
</head>
<body>
<div id='div-gpt-ad-123456789-0' style='width:320px; height:50px;'>
<script type='text/javascript'>
googletag.cmd.push(function() { googletag.display('div-gpt-ad-123456789-0'); });
</script>
</div>
</body>
</html>
java代码
WebView ad = (WebView) view.findViewById(R.id.ad);
ad.getSettings().setJavaScriptEnabled(true);
ad.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
// never gets here!
super.shouldOverrideUrlLoading(view, url);
return false;
}
@Override
public void onLoadResource(WebView view, String url) {
super.onLoadResource(view, url);
if (url.contains("googleads.g.doubleclick.net")) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
view.stopLoading();
}
}
});
ad.loadUrl("file:///android_asset/html/ad.html");