• About Us
  • Blog
  • Basket
  • Account
  • Sign In


Published on Wednesday, August 10, 2011

How to Add Google Ads to a Mobile Web Site

In the last few months I've had several questions from 51Degrees.mobi Framework users asking how to implement google adverts on their web sites. Google have a very simple piece of javascript that can be used with high end phones. However this won't work on all phones, and as those familiar with 51Degrees.mobi will know we don't like to exclude people because they don't have the high end phones. The ASP provided for all phones won't work in ASP.NET and requires some tweaking to get working. This blog explains how to use Google AdSense and an ASP.NET user control to get Google Ads on a web page in minutes.

Before adding any code to the web site we need to get the advert configuration settings from Google. If you haven't done so already you'll need to create a Google account and then choose Adsense. Use this link to get going.

From with in the Adsense menu choose AdSense Setup and a screen similar to the following will appear.

Google AdSense Setup
Choose AdSense for Mobile Content. On the following screen ensure the "All Phones" Device Type option is selected, shown highlighted in red in the screen below.

Configure the adverts the way you'd like them in the following screen. And then move to the final phase to get the code. A screen similar to the following should be displayed once ASP is selected.

The ASP code provided won't work on a regular ASP.NET page. However the parameters shown will determine how the advert will appear and you'll need to reference these.

Create a user control containing the following code in your project and/or web site.

<%@ Control Language="VB" AutoEventWireup="true" Inherits="System.Web.UI.UserControl" %>
<%@ Import Namespace="System" %>
<%@ Import Namespace="System.Math" %>
<%@ Import Namespace="System.Net" %>
<script runat="server">
Function googleColor(value, random)
  Dim colorArray
  colorArray = value.Split(",")
  googleColor = colorArray(random Mod (UBound(colorArray) + 1))
End Function
Function googleScreenRes()
  Dim screenRes, delimiter, resArray
   If Request.Browser.ScreenPixelsHeight > 0 And Request.Browser.ScreenPixelsWidth > 0 Then
      googleScreenRes = "&u_w=" & Request.Browser.ScreenPixelsWidth.ToString() & _
                        "&u_h=" & Request.Browser.ScreenPixelsHeight.ToString()
      Exit Function
   End If
  screenRes = Request.ServerVariables("HTTP_UA_PIXELS")
  delimiter = "x"
  If String.IsNullOrEmpty(screenRes) Then
    screenRes = Request.ServerVariables("HTTP_X_UP_DEVCAP_SCREENPIXELS")
    delimiter = ","
  End If
  If String.IsNullOrEmpty(screenRes) Then
    screenRes = Request.ServerVariables("HTTP_X_JPHONE_DISPLAY")
    delimiter = "*"
  End If
  resArray = Split(screenRes, delimiter, 2)
  If (UBound(resArray) + 1) = 2 Then
    googleScreenRes = "&u_w=" & resArray(0) & "&u_h=" & resArray(1)
  End If
End Function
Function googleMuid()
  Dim muid
  muid = Request.ServerVariables("HTTP_X_DCMGUID")
  If Not String.IsNullOrEmpty(muid) Then
    googleMuid = "&muid=" & muid
  End If
  muid = Request.ServerVariables("HTTP_X_UP_SUBNO")
  If Not String.IsNullOrEmpty(muid) Then
    googleMuid = "&muid=" & muid
  End If
  muid = Request.ServerVariables("HTTP_X_JPHONE_UID")
  If Not String.IsNullOrEmpty(muid) Then
    googleMuid = "&muid=" & muid
  End If
  muid = Request.ServerVariables("HTTP_X_EM_UID")
  If Not String.IsNullOrEmpty(muid) Then
    googleMuid = "&muid=" & muid
  End If
End Function
Function googleViaAndAccept(googleUserAgent)
  If Len(googleUserAgent) = 0 Then
    Dim via
    via = Server.URLEncode(Request.ServerVariables("HTTP_VIA"))
    If Not String.IsNullOrEmpty(via) Then
      googleViaAndAccept = "&via=" & via
    End If
    Dim accept
    accept = Server.URLEncode(Request.ServerVariables("HTTP_ACCEPT"))
    If Not String.IsNullOrEmpty(accept) Then
      googleViaAndAccept = googleViaAndAccept & "&accept=" & accept
    End If
  End If
End Function
Function GoogleAd_Load (sender, args)
    Dim googleTime, googleDt, googleScheme, googleUserAgent
    googleTime = DateDiff("s", "01/01/1970 00:00:00", Now())
    googleDt = (1000 * googleTime) + Round(1000 * (Now().Ticks - Int(Now.Ticks())))
    googleScheme = "http://"
    googleUserAgent = Server.URLEncode(Request.ServerVariables("HTTP_USER_AGENT"))
    If StrComp(Request.ServerVariables("HTTPS"), "on") = 0 Then googleScheme = "https://"
    Dim googleAdUrl
      "ad_type=text_image" & _
      "&channel=[YOUR_CHANNEL]" & _
      "&client=[YOUR_CLIENT]" & _
      "&color_border=" & googleColor("FFFFFF", googleTime) & _
      "&color_bg=" & googleColor("DAE9FD", googleTime) & _
      "&color_link=" & googleColor("2E69FF", googleTime) & _
      "&color_text=" & googleColor("333333", googleTime) & _
      "&color_url=" & googleColor("111180", googleTime) & _
      "&dt=" & googleDt & _
      "&format=mobile_single" & _
      "&ip=" & Server.URLEncode(Request.ServerVariables("REMOTE_ADDR")) & _
      "&markup=xhtml" & _
      "&oe=utf8" & _
      "&output=xhtml" & _
      "&ref=" & Server.URLEncode(Request.ServerVariables("HTTP_REFERER")) & _
      "&url=" & Server.URLEncode(googleScheme & Request.ServerVariables("HTTP_HOST") & Request.ServerVariables("URL")) & _
      "&useragent=" & googleUserAgent & _
      googleScreenRes() & _
      googleMuid() & _
    Dim googleAdOutput As New WebClient()
    CType(sender, Literal).Text = googleAdOutput.DownloadString(googleAdUrl)
End Function
<asp:Literal runat="server" ID="GoogleAd" OnLoad="GoogleAd_Load" />

Replace the parameters in the code above with the ones shown in the AdCode Google screen.

The user control can now be added to any web page and adverts will appear wherever the control is placed. Be aware it can take Google 48 hours to activate adverts so don't worry if nothing appears to start with. The resulting HTML will probably contain a placeholder comment during this initial period.

In this blog I've explained how to add Google mobile adverts to any ASP.NET web page which will work on any mobile device. It's a little fiddly because it's server side code and not simple javascript, but ultimately supporting all mobile devices will generate more advertising revenue which can't be bad.

Comments (0)

Author: Products Team

Categories: Development

Tags: Google , Mobile , Web

James Rosewell

Products Team

Other posts by Products Team
Contact author



.NET 2013 2014 4G 51Degrees 5G A.C.Roma A7 ABI Acer Adtech Affiliate Marketing Afilias Alcatel Amazon AMP Analysis Analytics Android Android 5.0 Lollipop Android Kitkat Android Lollipop Android Media Stick Apache API Apple Apple TV Archos Asha Asian Market ASP.NET Asus Australia Big Data Black Friday Blackberry Blink Browser C C# Case Study CeBIT CES Chrome Cloud CMS combinations Comparison Competition CoolPad COTW Cron CSS3 Data Data Blog Data File Data Model Daydream Denver Design Desire Eye Desktop Detection Developers Device Device Data Device Detection Device Intelligence Device Popularity Device property Device Types Device Use DeviceAtlas Display dmexco DoCoMo Doogee DotNetNuke Download Drupal Email EReader E-Reader Ericsson Evaluation Event Examples EXPLAY Rio Facebook feature Firefox Firefox OS Fly Foundation Framework France Galaxy S3 Galaxy S5 Galaxy Tab A Galaxy Tab A 8.0 Galaxy Tab A 9.7 Germany git repositories Global Google Google Daydream GSMA HAProxy Hardware Hisense HTC HTC ONE MAX HTC OS HTML5 HTTP HTTP Headers Huawei HUAWEI. UPDATE HUDL Huwaei IBC Icemobile Prime 4.0 IE IFA IIS Image Optimiser Image Optimizer India Infographic Ingeniux Internet usage iOS iOS 7 iOS 8 ipad iPhone iPhone 6 IsEmailBrowser IsWebApp Italy Japan Java Javascript Jolla Kentico Keynote Kindle Kindle Fire Kindle Fire HD Leagoo Lenovo LG Location Log File Analysis LTE Lumia m.dot macOS Map Memory Meta Data Mi 4S Micromax Microsoft Miia Style Mobile Mobile Analysis Mobile Analytics Mobile Devices Mobile Marketing Mixer Module Motorola MVC4 MWC MWC 2017 MWC16 MyPhone Native Native Apps NET New Release News News Letter Nexus Nexus 6 Nexus 9 NFC NGINX Nokia Nokia 3310 Non-Mobile NVIDIA Omate On7 OnePlus 5 Opera Opera Mini Operating System Optimisation OS OSX 10.10 OTA Panasonic Patent PC Pebble Performance phablet phone PHP Poland Presentation Press Release Price Band PRIV programmatic PS4 Publishers Python QMobile QR Codes Redirection Research Reseller Responsive Images Responsive web design RESS Review reviews RIM Ringmark RTB RWD Safari Samsung Scala ScientiaMobile Screen Screen resolution Screen Size SEO Server Server-side optimisation Set Box Set Top Box Sharepoint Shark 1 SHIFT phones Sitecore Sitecore version 9 SLUSH Smart TV Smartphone Smartphones Smartwatches Snapdragon Sony Sony Xperia Spain Swedish Beers Symbian Tablet Tablets Tesco Testing Tips Top 5 TOTW TV UDS UK Umbraco Update updates US User Agent UserAgent User-Agent Vendors Version 3 Video VoLTE VR Wearable Web Web Apps Web content management WebKit WebMatrix White Paper Widgets Widnows WiFi Wiko Wileyfox Windows Windows Phone WURFL Xbox XBox One Xiaomi Xperia Xperia z Yosemite Z10 ZenFon 2 ZOPO ZTE