Develop ads for the Google Mobile Ads SDK

Attention Android developers:

On August 1, 2014, Google Play stopped accepting new or updated apps that use the old standalone Google Mobile Ads SDK v6.4.1 or lower. You must upgrade to the Google Play version of the Mobile Ads SDK.

MRAID compatibility

The Google Mobile Ads SDK supports the IAB's Mobile Rich Media Ad Interface Definitions (MRAID) standard for advertising in mobile apps (currently in an open beta release). You can set a line item as MRAID v1 or MRAID v2 through the line item targeting settings, under Devices > Device capability.

MRAID v2 requires Google Play services v7.8 or higher for Android and Google Mobile Ads SDK v7.4.0 or higher for iOS. To use MRAID functions in your ad creatives, you must import mraid.js into your creative. To do this, include <script src="mraid.js> in your creative. The Google Mobile Ads SDK, as an MRAID-compatible SDK, will look for that code in the creative and replace it with an actual URL pointing to an implementation of MRAID. Other SDKs that support MRAID will do the same though their actual URLs would be different. You can optionally include the MRAID libraries, as well as the Google Mobile Ads SDK functionality, in the same creative.

Learn more about MRAID support in the developer documentation.

Google Mobile Ads SDK functionality

To take advantage of the functionality of the Google Mobile Ads SDK, you can use the JavaScript functions exposed by the google.mobile.app.ads class. You must include the following code in the <head> section of the creative:

Access to device capabilities

The SDK also exposes the capabilities of the in-app browsers available on iOS and Android. This allows developers to access device capabilities such as the accelerometer, gyroscope and compass via HTML5 where the platform supports them. Please refer to the documentation for each platform for more information on these capabilities and how to access them.

App events
App events (3:16)

App events enable you to execute custom code in your application when a creative dispatches an app event. With app events, you can introduce custom ad executions that interact with the application, such as changing the background color of the app.

Learn how to implement app events.

Scaling image to full screen

If you find that your full screen ad is only taking up part of the screen, insert the following code in the <head> section of the creative:

<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no"/>.

Sample code for a rotatable ad

You can use the code below to serve a rotatable ad.

<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <style>
      * {
        padding: 0px;
        margin: 0px;
        border: none;
      }

      a { display: block }

      #landscape{ display: none; }

      /* Portrait */
      @media screen and (orientation:portrait) {
        #portrait { display: block; }
	#landscape { display: none; }
      }
      /* Landscape */
      @media screen and (orientation:landscape) {
        #portrait { display: none; }
	#landscape { display: block; }
      }
    </style>
  </head>
  <body>
    <a href="%%CLICK_URL_UNESC%%[%ClickThroughURL%]">
      <img id="portrait" src="[%PortraitImageFile%]" width="[%PortraitImageWidth%]" height="[%PortraitImageHeight%]"/>
      <img id="landscape" src="[%LandscapeImageFile%]" width="[%LandscapeImageWidth%]" height="[%LandscapeImageHeight%]"/>
    </a>
  </body>
</html>

Sample code for in-app: Mobile Click To Calendar using MRAID v2.0

This template is a banner ad unit that starts off as a bottom screen banner. If a user clicks on the banner, then their default calendar application will create a new event with their consent.

Behavior and UI elements

The creative comprises the following UI elements:

  • The banner image and its height + width.
  • Information about the event is required such as the summary, description, location, start date and end date.
Name Type Required Description
Banner Image File File Yes Image of the banner ad.
Banner Image Width Number Yes Width of the Banner Image.
Banner Image Height Number Yes Height of the Banner Image.
Event Summary Text Yes Summary of the event.
Event Description Text Yes Description of the event.
Event Location Text No Location of the event.
Event Start date Text Yes The start date of the event. The start date should take the following form: '2016-10-22T00:00-05:00'. For example this is 22nd October 2016 from 0:00 to 05:00.
Event End date Text Yes The end date of the event. The end date should take the following form: '2016-10-22T00:00-05:00'. For example this is 22nd October 2016 from 0:00 to 05:00.

<html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"/>
<head>
<script type="text/javascript" src="mraid.js"></script>
</head>
<body>
<div id="normal" style="display:none; margin:auto;top:0px;text-align:center">
<a href="#" onClick="addToCalendar()"; return false;>
<img width="[%BannerImageWidth%]" height="[%BannerImageHeight%]" src="[%BannerImageFile%]" />
</a>
</div>
<script>

// Check whether mraid is ready by adding event listener
function doReadyCheck(){
  if(mraid.getState() == 'loading'){
    mraid.addEventListener("ready", mraidIsReady);
  }else{
    showMyAd();
  }
}

// Once mraid is ready, it does not need to listen to the ready event anymore
function mraidIsReady(){
  mraid.removeEventListener("ready", mraidIsReady); 
  showMyAd();
}

// Only show Ad when mraid is ready
function showMyAd(){
  var advertElement = document.getElementById("normal");
  advertElement.style.display = 'block';
}

// Add event to the calendar using appropriate input if the device supports calendar manipulation
function addToCalendar(){

  // Register the click by creating an image
  var x = document.createElement("IMG");
  x.setAttribute("src", "%%CLICK_URL_ESC%%");
  window.top.document.body.appendChild(x);

  if(mraid.getVersion()=="2.0"){
    mraid.createCalendarEvent({summary: "[%EventSummary%]", description: "[%EventDescription%]", location: "[%EventLocation%]", start: "[%EventStartDate%]", end: "[%EventEndDate%]"}); 
  } 
  return false;
}

doReadyCheck();
</script>
</body>
</html>

Test adunit name: ali_Calendar

Sample code for display: Expandable Footer Template using MRAID v2.0

This template is a two-component ad unit that starts off as a bottom screen banner. If a user clicks on the banner, then the ad will resize to some specific dimensions. If the bigger ad is clicked on, then the user is redirected to a specific website.

The width can be either the size of the banner or it takes up the whole width (if FullWidthResize is true).

Behavior and UI elements

The creative comprises the following UI elements:

  • Creative Assets (for each of these assets, the file, height and width are required)
    • Banner Image component
    • Resized Banner component
    • Close button icon
  • Can adjust the position of the close button so that it is either on the top right or top left of the screen.
  • Can change the background color of the ad.
Name Type Required Description
Banner Image File File Yes Image that will be displayed in the banner ad.
Banner Image Height Number Yes The height of the banner image.
Banner Image Width Number Yes The width of the banner image.
Background Color Text Yes The background colour of the space occupied by the resized image and of the space occupied by the banner.
ClickThrough URL URL Yes The URL that the user will be redirected to when the resized ad has been clicked on.
Resized Image File File Yes The image that will be displayed when the banner has been clicked on.
Resized Image Height Number Yes The height of the resized image.
Resized Image Width Number Yes The width of the resized image.
Close Icon File Yes The image file for the “close” button.
Close Icon Width Number Yes The width of the “close” button. (30 is the average width).
Close Icon Height Number Yes The height of the “close” button. (30 is the average height).
Position Of Close Button List No Can position the “close” button so that it is on the top right or top left of the screen. Possible values are “Right” or “Left”. If this is left blank, then it will position the close button to the top right of the screen.
Full Width Resize List No Can make the resized ad take up the entire width of the screen if the value is “Yes”. If the value is “No”, then the width will be the same size as the original banner. Possible values are “Yes” and “No”, the default is “No”.


<html><meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"/>
<head>
<script type="text/javascript" src="mraid.js"></script>
<style>
#close_button {
  position: absolute;
  top: 4px;
  right: 4px;
  display:block;
}

#resized img {
  display : block;
  margin : auto;
}
</style>
</head>
<body>
<div id="normal" style="display:none; margin:auto;top:0px;text-align:center">
<a onClick="resize();">
<img width="[%BannerImageWidth%]" height="[%BannerImageHeight%]" src="[%BannerImageFile%]"  />
</a>
</div>

<div id="resized" style="display:none; top:0px;">
<a onClick="openURL()">
<img width="[%ResizedImageWidth%]"  height="[%ResizedImageHeight%]" src="[%ResizedImageFile%]"/>
</a>
<div id="close_button">
<img width="[%CloseIconWidth%]" height="[%CloseIconHeight%]" src="[%CloseIcon%]"/> 
</div>
</div>

<script>
<!--

// Variables
var closeButton = document.getElementById("close_button");
var bodyElement = document.body;
var advertElement = document.getElementById("normal");
var resizedElement = document.getElementById("resized");
var resizeBannerWidth;

function changeBodyElementStyle() {
  // Change background color
  if ("[%ResizedBackgroundColor%]") {
    bodyElement.style.backgroundColor = "[%ResizedBackgroundColor%]";
    resizedElement.style.backgroundColor = "[%ResizedBackgroundColor%]";	
  }
}

function openURL() {
  mraid.open("%%CLICK_URL_ESC%%[%ClickThroughURL%]");
}

//Check whether MRAID is ready by adding event listener
function checkIfReady(){
  if(mraid.getState() == 'loading'){
    mraid.addEventListener("ready", mraidIsReady);
  } else{
    showMyAd();
  }
}

function mraidIsReady(){
  mraid.removeEventListener("ready", mraidIsReady); 
  showMyAd();
}

// Set resizing properties and resize
function resize(){
	// If FullWidthResize is "Yes", then the resized advert takes up the whole width. Otherwise takes up the width of the original banner
	if ("[%FullWidthResize%]" == "Yes") {
	    resizeBannerWidth = screen.width;
	} else {
	    resizeBannerWidth = mraid.getDefaultPosition().width;
	}	
	
  if(mraid.getVersion()=="2.0"){
    if ("[%PositionOfCloseButton%]" === "Left") {
	  closeButton.style.left = "0";

mraid.setResizeProperties({"width":""+resizeBannerWidth+"","height":"[%ResizedImageHeight%]","offsetX":"","offsetY":"","customClosePosition":"top-left", "allowOffscreen":false});
	} else {
	  closeButton.style.right = "0";

mraid.setResizeProperties({"width":""+resizeBannerWidth+"","height":"[%ResizedImageHeight%]","offsetX":"","offsetY":"","customClosePosition":"top-right", "allowOffscreen":false});
	}
    mraid.resize();
	return false;
  }
  else{
    return true;
  }
}

// Displays the advert and add an event listener to it to detect whether to resize
function showMyAd(){
  advertElement.style.display = "inline";
  mraid.addEventListener("stateChange",updateAd); 
}

// updateAd is called when MRAID changes state - calls toggleLayer to expand/ reduce ad size
function updateAd(state){
  if (state == "resized"){
    toggleLayer('normal', 'resized');
  }else if(state == "default"){
    toggleLayer('resized', 'normal');
  }
}

// Goes to the other state (either resized or banner)
function toggleLayer(fromLayer, toLayer){
  var fromLayerElem = document.getElementById(fromLayer);
  fromLayerElem.style.display = 'none';
  var toLayerElem = document.getElementById(toLayer);
  toLayerElem.style.display = 'block';
}

changeBodyElementStyle();
checkIfReady();
//-->
</script>
</body>
</html>

Test adunit name: ali_resizeBanner

Sample code for in-app: Mobile Expandable Banner (MRAID 2.0) Using Default Close Button

This template is a two component ad unit that starts off as a bottom screen banner. If a user clicks on the banner, then the ad will expand to cover the whole screen. If the bigger ad is clicked on, then the user is redirected to a specific website. It utilises the default MRAID close button.

Behavior and UI elements

The creative comprises the following UI elements:

  • Creative Assets:
    • Banner Image component (height and width are also required)
    • Expand Banner component
  • Can change the background color of the banner ad and the expanded ad
Name Type Required Description
Banner Image File File Yes Image that will be displayed in the banner ad.
Banner Image Height Number Yes The height of the banner image.
Banner Image Width Number Yes The width of the banner image.
Background Color Text Yes The background color of the space occupied by the banner image.
ClickThrough URL URL Yes The URL that the user will be redirected to when the resized ad has been clicked on.
Expanded Image File File Yes The image that will be displayed when the banner has been clicked on.
Expanded Image Height Number Yes The height of the expanded image.
Expanded Image Width Number Yes The width of the expanded image.

       
<html><meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"/>
<head>
<script type="text/javascript" src="mraid.js"></script>
</head>
<body>
<div id="normal" style="display:none; margin:auto;top:0px;text-align:center">
<a onClick="expand();">
<img width="[%BannerImageWidth%]" height="[%BannerImageHeight%]" src="[%BannerImageFile%]" />
</a>
</div>
<div id="expanded" style="display:none;top:0px;text-align:center">
<a onClick="openURL()">
<img width="[%ExpandedImageWidth%]"  height="[%ExpandedImageHeight%]" src="[%ExpandedImageFile%]" />
</a>
</div>

<script>
<!--

function openURL() {
  mraid.open("%%CLICK_URL_ESC%%[%ClickThroughURL%]");
}

// Change background color if present
function changeBodyElementStyle() {
  if ("[%BackgroundColor%]") {
    var bodyElement = document.body;
    bodyElement.style.backgroundColor = "[%BackgroundColor%]";
  }
}	

// Check whether MRAID is ready by adding event listener
function checkIfReady(){
  if(mraid.getState() == 'loading'){
    mraid.addEventListener("ready", mraidIsReady);
  } else{
    showMyAd();
  }
}

// Once MRAID is ready, it does not need to listen to the ready event anymore
function mraidIsReady(){
  mraid.removeEventListener("ready", mraidIsReady); 
  showMyAd();
}

function showMyAd(){
  // Displays the advert
  var advertElement = document.getElementById("normal");
  advertElement.style.display = "inline";

  // Add event listener to detect whether to expand or not
  mraid.addEventListener("stateChange",updateAd); 

  // Change background color of the expanded advert
  var expandedDiv = document.getElementById("expanded");
  if ("[%BackgroundColor%]") {
    expandedDiv.style.backgroundColor = "[%BackgroundColor%]";
  }
}

function expand() {
  if(mraid.getVersion()=="2.0"){
    mraid.expand();
    return false;
  }
  else {
    return true;
  }
}

// updateAd is called when mraid changes state
// Calls toggleLayer to expand/ reduce ad size
function updateAd(state){
  if (state == "expanded"){
    toggleLayer('normal', 'expanded');
  }else if(state == "default"){
    toggleLayer('expanded', 'normal');
  }
}

// Goes to the other state (either expands or banner)
function toggleLayer(fromLayer, toLayer){
  var fromLayerElem = document.getElementById(fromLayer);
  fromLayerElem.style.display = 'none';
  var toLayerElem = document.getElementById(toLayer);
  toLayerElem.style.display = "block";
}

changeBodyElementStyle();
checkIfReady();
//-->
</script>
</body>
</html>


Test adunit name: ali_expandDefaultClose

Sample code for in-app: Mobile Expandable Banner (MRAID 2.0) Using Custom Close Button

This creative is a two component ad unit that starts off as a bottom screen banner. If a user clicks on the banner, then the ad will expand to cover the whole screen. If the bigger ad is clicked on, then the user is redirected to a specific website.

This creative allows the use of a custom close button (can adjust the height, width, appearance and position of the button).

Behavior and UI elements

The creative comprises the following UI elements:

  • Creative Assets:
    • Banner Image component (height and width are also required)
    • Expand Banner component
  • Can change the background color of the banner ad and the expanded ad
  • Uses a custom close button.
Name Type Required Description
Banner Image File File Yes Image that will be displayed in the banner ad.
Banner Image Height Number Yes The height of the banner image.
Banner Image Width Number Yes The width of the banner image.
Background Color Text Yes The background color of the space occupied by the banner image.
ClickThrough URL URL Yes The URL that the user will be redirected to when the resized ad has been clicked on.
Expanded Image File File Yes The image that will be displayed when the banner has been clicked on.
Expanded Image Height Number Yes The height of the expanded image.
Expanded Image Width Number Yes The width of the expanded image.
Close Icon File Yes The image file for the “close” button.
Close Icon Width Number Yes The width of the “close” button. (30 is the average width).
Close Icon Height Number Yes The height of the “close” button. (30 is the average height).


<html><meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"/>
<head>
<script type="text/javascript" src="mraid.js"></script>

<style>
<!--
#close_button {
position: absolute;
top: 0px;
right: 0px;
display: block;
}
//-->
</style>

</head>
<body>
<div id="normal" style="display:none; top:0px;">
<a onClick="expand();">
<img width="[%BannerImageWidth%]" height="[%BannerImageHeight%]" src="[%BannerImageFile%]" />
</a>
</div>
<div id="expanded" style="display:none;top:0px;text-align:center">
<a onClick="openURL()">
<img width="[%ExpandImageWidth%]"  height="[%ExpandImageHeight%]" src="[%ExpandImageFile%]" />
</a>
<div id="close_button">
<img width="[%CloseIconWidth%]" height="[%CloseIconHeight%]" src="[%CloseIcon%]"/> 
</div>
</div>

<script>
<!--

function openURL() {
	mraid.open("%%CLICK_URL_ESC%%[%ClickThroughURL%]");
}


// Change background color if present
function changeBodyElementStyle() {
	if ("[%BackgroundColor%]") {
	  var bodyElement = document.body;
      bodyElement.style.backgroundColor = "[%BackgroundColor%]";
  }
}

// Check whether MRAID is ready by adding event listener
function checkIfReady(){
  if(mraid.getState() == 'loading') {
    mraid.addEventListener("ready", mraidIsReady);
  } else{
    showMyAd();
  }
}

// Once MRAID is ready, it does not need to listen to the ready event anymore
function mraidIsReady(){
  mraid.removeEventListener("ready", mraidIsReady); 
  showMyAd();
}

function showMyAd(){
  // Displays the advert
  var advertElement = document.getElementById("normal");
  advertElement.style.display = "inline";

  // Add event listener to detect whether to expand or not
  mraid.addEventListener("stateChange",updateAd); 

  // Change background color of the expanded advert
  var expandedDiv = document.getElementById("expanded");
  expandedDiv.style.backgroundColor = "[%BackgroundColor%]";
}

// updateAd is called when mraid changes state
// Calls toggleLayer to expand/ reduce ad size
function updateAd(state){
  if (state == "expanded"){
    toggleLayer('normal', 'expanded');
  }else if(state == "default"){
    toggleLayer('expanded', 'normal');
  }
}

// Goes to the other state (either expands or banner)
function toggleLayer(fromLayer, toLayer){
  var fromLayerElem = document.getElementById(fromLayer);
  fromLayerElem.style.display = 'none';
  var toLayerElem = document.getElementById(toLayer);
  toLayerElem.style.display = "inline";
}

// Expand ad and make the close button visible for the user			
function expand() {
   if(mraid.getVersion()=="2.0"){
    document.getElementById("close_button").style.visibility = "visible";
    mraid.setExpandProperties({"width": "[%ExpandImageWidth%]", "height": "[%ExpandImageHeight%]", "useCustomClose": true}); 
    mraid.expand();
    return false;
  }
  else {
    return true;
  }
}

changeBodyElementStyle();
checkIfReady();
//-->
</script>
</body>
</html>


Test adunit name: ali_expandCustomClose

Sample code for display: Expandable Footer Template (without using MRAID 2.0)

This template is a two component ad unit that starts off as a bottom screen banner. If a user clicks on the banner, then the ad will resize to some specific dimensions. If the bigger ad is clicked on, then the user is redirected to a specific website.

It also has a custom close button, which is used to restore the ad back to its banner state.

Behavior and UI elements

The creative comprises the following UI elements:

  • Creative Assets (for each of these assets, the file, height and width are required)
    • Banner Image component
    • Expand Banner component
    • Close button icon
  • Can adjust the position of the close button so that it is either on the top right or top left of the screen.
  • Can change the background color of the ad.
Name Type Required Description
Banner Image File File Yes Image that will be displayed in the banner ad.
Banner Image Height Number Yes The height of the banner image.
Banner Image Width Number Yes The width of the banner image.
Background Color Text Yes The background color of the space occupied by the resized image.
ClickThrough URL URL Yes The URL that the user will be redirected to when the resized ad has been clicked on.
Resized Image File File Yes The image that will be displayed when the banner has been clicked on.
Resized Image Height Number Yes The height of the resized image.
Resized Image Width Number Yes The width of the resized image.
Close Icon File Yes The image file for the “close” button.
Close Icon Width Number Yes The width of the “close” button. (30 is the average width).
Close Icon Height Number Yes The height of the “close” button. (30 is the average height).
Close Button Position List No Can position the “close” button so that it is on the top right or top left of the screen. Possible values are “Right” or “Left”. If this is left blank, then it will position the close button to the top right of the screen.


<html><meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"/>
<head>
<style>
#close_button {
position: absolute;
top: 1%;
display:block;
}
#advertArea {
position:absolute; 
width:100%;
height:100%;
top:0;
left: 0;				
}
</style>
</head>
<body>
<div id="normal" style="display:block; margin:auto;top:0px;text-align:center">
<img width="[%BannerImageWidth%]" height="[%BannerImageHeight%]" src="[%BannerImageFile%]" onClick="showBiggerAdvert();" />
</div>

<div id="resized" style="display:none;top:0px;text-align:center;";>
<a href="%%CLICK_URL_ESC%%[%ClickThroughURL%]">
<span id="advertArea"> </span>
<img width="[%ResizedImageWidth%]"  height="[%ResizedImageHeight%]" src="[%ResizedImageFile%]" />
</a>
<div id="close_button">
<img width="[%CloseIconWidth%]" height="[%CloseIconHeight%]" src="[%CloseIcon%]" onClick="showOriginalBanner()"/> 
</div>
</a>
</div>

<script>

// Variable assignments
var closeButton = document.getElementById("close_button");
var resizedDiv = document.getElementById("resized");
var bannerDiv  = document.getElementById("normal");

function changeBodyElementStyle() {
  // Change background color
  if ("[%BackgroundColor%]") {
    var bodyElement = document.body;
    bodyElement.style.backgroundColor = "[%BackgroundColor%]";
  }

  // Shift Close button position
  if ("[%CloseButtonPosition%]" === "Left") {
    closeButton.style.left = "0";
  } else {
    closeButton.style.right = "0";
  }
}

// Resize advert to make it bigger	
function showBiggerAdvert(){
  toggleLayer('normal', 'resized');
}

// Hide the resized advert and show the original banner
function showOriginalBanner() {
  toggleLayer('resized', 'normal');
}

// Goes to the other state (either resized or banner)
function toggleLayer(fromLayer, toLayer){
  var fromLayerElem = document.getElementById(fromLayer);
  fromLayerElem.style.display = 'none';
  var toLayerElem = document.getElementById(toLayer);
  toLayerElem.style.display = 'block';
}

changeBodyElementStyle();
</script>
</body>
</html>


Sample code for an expandable ad (MRAID v1 and non-MRAID versions)

MRAID example

For more information, please refer to the developer documentation..

<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="user-scalable=no, width=device-width,initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"/>
    <script type="text/javascript" src="mraid.js"></script>
    <style type="text/css">
      html, body {
        margin: 0;
        padding: 0;
      }

      .banner, .overlayBanner {
        display: block;
        position: absolute;
        top: 0px;
        left: 0px;
        z-index: 1000;
        overflow: hidden;
      }

      .banner {
        background-color: black;
        width: 300px;
        height: 50px;
      }

      .overlayBanner {
        background-color: green;
        width: 300px;
        height: 250px;
      } 
    </style>
    <script type="text/javascript">
      // Check to see if document is ready
      if ((mraid.getState() != "default") || (mraid.getState() != "ready")) {
        // console.log("Document is not ready, adding event listener");
        // Register event listener to keep track of state changes
        mraid.addEventListener("stateChange", handleStateChanges);
      } else {
        // console.log("Document is ready");
        // Register event listener to keep track of state changes
        mraid.addEventListener("stateChange", handleStateChanges);
      }

      function handleStateChanges() {
        // console.log('mraid state: ' + mraid.getState());
        // Perform action on state change
        switch(mraid.getState()) {
        case "expanded":
          // console.log("handleStateChanges, expanded");
          // Show the overlay banner when view is in "expanded" state
          document.getElementById('banner').setAttribute('class', 'overlayBanner');
          break;
        case "default":
          // console.log("handleStateChanges, default");
          // Show the initial banner when view is in "default" state
          document.getElementById('banner').setAttribute('class', 'banner');
          break;
        }
      }
</script>
</head>

<body>
<div id='banner' onClick='mraid.expand()'></div>
</body>

</html>

Non-MRAID example, using creative templates

You can use the sample code below to serve a banner to a mobile application. On click, the banner expands to a full-screen unit displayed in an overlay window inside the application. In the sample code, replace the following placeholder elements with your own values:

  • [FALLBACK_CLICKURL]: Backup landing page in case JavaScript function doesn't get called.
  • [FULLSCREEN_UNIT]: URL of full screen ad unit.
  • [ORIENTATION]: Supported orientation for full screen unit (use "p" for portrait, "l" for landscape, or omit this value to allow any orientation).
  • [BANNER_UNIT]: URL of banner image.
  • [WIDTH]: Width of banner.
  • [HEIGHT]: Height of banner.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"/>

<script type="text/javascript" src="http://media.admob.com/api/v1/google_mobile_app_ads.js"></script>
</head>

<body>
<a href="[FALLBACK_CLICKURL]" onClick="admob.opener.openOverlay('%%CLICK_URL_ESC_ESC%%[FULLSCREEN_UNIT]', '[ORIENTATION]'); 
return false;"><img border="0" src="[BANNER_UNIT]" width="[WIDTH]" height="[HEIGHT]"></a>
</body>

</html>

Sample code for automatically closing an interstitial
Only directly-booked interstitials can be automatically closed; interstitials served via dynamic allocation (i.e., Ad Exchange, AdSense or AdMob) can only be dismissed by the user.

To make an interstitial close after a fixed period of time:

  • Include code in the creative to close the interstitial after a fixed period of time has elapsed. The following code can be used as a template for this approach:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"/>
      <script type="text/javascript" src="http://media.admob.com/api/v1/google_mobile_app_ads.js"></script>
      <script>
        <!--
          function
          _admStartCountDown(){setTimeout('admob.opener.close()',parseInt('[%displayTime%]')*1000)}
          function
          _admOnload(){if(admob.opener.isOverlayShowing()){_admStartCountDown()}else{admob.events.addEventListener('onshow',
          _admStartCountDown)}}
          if(window.addEventListener){window.addEventListener("load",_admOnload,false)}else{window.attachEvent("onload",_admOnload)}
        //-->
      </script>
  </head>
  <body>
    [Your_AdCode_Goes_Here]
  </body>
</html>
Target window: in-app overlay window

Using admob.opener.openOverlay(), you can open a full screen overlay browser that is animated from the bottom of the screen. This browser does not include a status bar and always displays a close button at the upper-left corner. This option can work nicely for an expandable ad where the full screen unit can be hosted on a separate page (see the sample code for an expandable ad).

Below is sample code for a simple banner where the full screen unit can be loaded into an overlay browser window. You should replace the following placeholder elements with your own values. If available for your network, you can use the sample code to create a creative template.

  • [BANNER_UNIT]: URL of a banner creative.
  • [WIDTH]: Width of a banner creative.
  • [HEIGHT]: Height of a banner creative.
  • [FULLSCREEN_UNIT]: URL of a full screen creative. Note: Full screen unit should include JavaScript code to parse the destination URL and redirect the user to the landing page upon receiving a click action. See Handling destination URL from a full screen unit for more details.
  • [DESTINATION_URL]: URL of a destination page.
  • [FALLBACK_URL]: Fallback destination URL to use in case JavaScript function doesn't execute.
  • [ORIENTATION]: Supported orientation for destination URL (use "p" for portrait, "l" for landscape, or omit this value to allow any orientation).

Here's a sample creative code:

<!DOCTYPE html>
<head>
<meta name="viewport" 
content="user-scalable=no, width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"/>

<script type="text/javascript" src="http://media.admob.com/api/v1/google_mobile_app_ads.js"></script>
</head>

<body>
<a href="[FALLBACK_CLICKURL]" 
onClick="admob.opener.openOverlay('%%CLICK_URL_ESC%%[FULLSCREEN_UNIT]?destination=[DESTINATION_URL]', 
'[ORIENTATION]'); return false;"><img border="0" 
src="[BANNER_UNIT]" width="[WIDTH]" height="[HEIGHT]"></a>
</body>
</html>

Handling destination URL from a full screen unit

The admob.opener.openOverlay() function does not have the option to specify the destination URL of the html content. Assuming that you've passed the destination URL in the form of key-value pair when specifying the fullscreen unit, e.g. "http://link.to.fullscreen.unit?destination=http://my.destination.url", you can write a simple JavaScript function and include a snippet of HTML code to capture the click and redirect the user to the destination page.

 

Here's a sample page source:

<!DOCTYPE html>
<head>
<meta name="viewport" 
content="user-scalable=no, width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"/>

<script type="text/javascript" src="http://media.admob.com/api/v1/google_mobile_app_ads.js"></script>

<script type="text/javascript">
function destinationUrl() {
  // Get current url after ?
  var destinationUrl = window.location.search;

  // Strip off the leading '?'
  destinationUrl = destinationUrl.substring(1);
  // Parse destination=url key-value pair
  var kvPair = destinationUrl.split("=");
  var key = kvPair[0]; // key: destination
  var value = kvPair[1]; // value: url
  var url = decodeURIComponent(value); 

  // Open destination inside overlay
  window.location = url;

  // Open destination in an external browser
  // admob.opener.openUrl(url, true);
}
</script>
</head>

<body>
<div style="position:relative;">
<!-- Load content source into an iframe -->
<iframe src="http://creative.admob.com/t1/bestBuy/tradeinJul/gi/" 
align="middle" frameborder=0 width=320 height=480 marginheight=0 marginwidth=0 scrolling=no></iframe>
<!-- Create a clickable area -->
<a href="#" onClick="destinationUrl(); return false;" style="position:absolute; top:0; left:0; 
display:inline-block; width:320px; height:480px; z-index:5;"></a>
</div>
</body>
</html>
Target window: new browser window

Using admob.opener.openUrl(), you can open a new native browser window (outside the application). Below is sample code for a simple banner where the destination URL can be loaded into a new browser window. You should replace the following placeholder elements with your own values. If available for your network, you can use the sample code to create a creative template.

  • [BANNER_UNIT]: URL of a banner creative.
  • [WIDTH]: Width of a banner creative.
  • [HEIGHT]: Height of a banner creative.
  • [FULLSCREEN_UNIT]: URL of a full screen creative.
  • [FALLBACK_URL]: Fallback destination URL to use in case the JavaScript function doesn’t execute.

Here's a sample creative code:

<!DOCTYPE html>
<head>
<meta name="viewport" 
content="user-scalable=no, width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"/>

<script type="text/javascript" src="http://media.admob.com/api/v1/google_mobile_app_ads.js"></script>
</head>

<body>
<a href="[FALLBACK_CLICKURL]" 
onClick="admob.opener.openUrl('%%CLICK_URL_ESC%%[FULLSCREEN_UNIT]', true); 
return false;"><img border="0" src="[BANNER_UNIT]" width="[WIDTH]" height="[HEIGHT]"></a>
</body>
</html>

 

Also see the AdMob Guide to Mobile Ad Development.
Was this article helpful?