Sunday, August 12, 2012

jQuery Mobile and AdSense



You and your team create a beautiful and engaging mobile website. Your visitors, page views, and site duration numbers keep increasing, but how do you turn that into cash? Like it or not one of the easiest ways to turn page views into cash is ads. That's right ads, those annoying things that all users seem to hate but are the most universal way to pay the bills.

In this post I show how to integrate Google AdSense into a jQuery Mobile web site. Please know that AdSense is not the only mobile web ad provider, there are others and I would highly recommend investigating them before committing to AdSense.


Like so many things Google there is a "Getting started" page. It is a little bit hard to find since most search queries for mobile ads will send you to AdSense's cousin, AdMob which is intended for mobile device apps. Be sure to read all of the program policies. You and your site will be held responsible if you violate any policy. 

Next you will need to sign into AdSense with a Google Account, aka your GMail account. If you don't have one you will need to get one which is relatively easy to do. Be aware that this account will need to be verified. Since AdSense will hopefully be sending you money, both your identity, address, and banking information will need to verified.

Once you are in AdSense do the following:

  1. Click the My ads tab
  2. Make sure that Ad units is selected in the left column
  3. Click the + New ad unit button
  4. Give the ad unit a name, I chose, BlogDemo
  5. Set the Ad size, choose 320 x 50 - Mobile Banner
  6. Make sure that Text & image/rich media ads is selected
  7. For Backup ads, just leave it set to Show blank space
  8. Don't worry about Custom channels
  9. Leave the Ad style set to Google default
  10. Click the button Save and get code
  11. Copy the Ad code


The Ad code will look something like the following:

<script type="text/javascript"><!--
google_ad_client = "ca-pub-################";
/* BlogDemo */
google_ad_slot = "6806436256";
google_ad_width = 320;
google_ad_height = 50;
//-->
</script>
<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>

There are two parts to the Ad code, the first part should go in the header of each page which will display an ad. The second part should go where the ad will be displayed. In the first part is your Google Ad Client Publisher Id. You must replace the number shown with yours. The number shown above will not work in code.

To demonstrate how to plug the ad code in, let's create a simple two page mobile website. If you've read this blog before, you might recognize this as our jQuery Mobile Skeleton. It makes a good place to start our coding.

Where should we display the ad? Since the ad is 320 x 50, it will stretch the width of the display on iPhones and many other smart phones. Obviously we don't want an ad appearing over out content. It would be least bothersome either at the top or the bottom of the page. Or in jQuery Mobile parlance, it will be best if was in either in the header or the footer. And that is exactly what we will do.

First we place the first part of the Ad code in the head section of both pages:

<script src="scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
<script src="scripts/jquery.mobile-1.1.1.min.js" type="text/javascript"></script>
<script type="text/javascript"><!--
        google_ad_client = "ca-pub-################";
        /* BlogDemo */
        google_ad_slot = "6806436256";

        google_ad_width = 320;
        google_ad_height = 50;
        //-->
</script>

On page one we will place the ad in the footer like so:

<footer data-role="footer" data-position="fixed">
        <script type="text/javascript"
                src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
        </script>
</footer>

Notice that we use the data-position="fixed". That will lock our ad at the bottom of the display.

On page two, we place the ad in the header like so:

<header data-role="header" data-position="fixed">
        <script type="text/javascript"  data-ajax="false"
                src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
        </script>
</header>

The last thing we need to do is force page loads. AdSense was created for websites which load pages the old fashion way. It uses the HTML <script> tag to inject JavaScript and HTML onto the page. If the script tag is loaded via ajax, the magic doesn't occur. To get this behavior in jQuery Mobile, we must turn ajax off via the data-ajax="false" attribute.

<a href="index.html"  data-role="button" data-ajax="false">to the Index page</a> 

Unfortunately, while the data-ajax allows AdSense to function correctly, it causes us to lose the jQuery Mobile transition effects. If anyone has found a way around this, please let me know.

The code for this post is on GitHub as always. Keep in mind that it won't work until you put your publisher information in.


20 comments:

  1. I got excited when I saw the post. I thought you had figure a way to keep Ajax working while using Adsense.

    Google should really take a look at this problem and solve it.

    ReplyDelete
    Replies
    1. I've heard rumors of a JavaScript API coming. That it would be more like Google Maps, giving the user a way to refresh ads via method calls. Any Googlers able to confirm?

      Troy

      Delete
  2. Thanks for the tutorial!

    FYI: The link to "JQM AdSense Live Demo (best from your smart phone)" is pointing to your localhost.

    ReplyDelete
  3. Thanks! This helped a lot. Did you ever figure out how to get transitions back?

    ReplyDelete
  4. Thanks Troy! Been looking for the data-ajax="false" solution. Will post if I find way to maintain transitions.

    ReplyDelete
    Replies
    1. Thanks for reading my humble blog. I will have more on supporting ads from JQM soon. I always announce new post to Google+ and twitter @therockncoder, so you may want to follow.

      Delete
  5. On the same topic, I was trying to do this globally so not having to edit all pre-existing links. I have found this:


    $(document).bind("mobileinit", function () {
    $.mobile.ajaxEnabled = false;
    });



    I put in where include my JQ and JQM scripts, but it doesn't seem to work. Just wanted to throw this out also for another option (if it can be made to work).

    ReplyDelete
  6. Follow Up: I did get the global disabling of ajax to work properly. It is the order of the inclusion of the JQ items in the page that mattered (in my case anyway). They had to be in this order:

    1. JQ CSS file
    2. JQ core library
    3. the script that disables ajax (see prior post)
    4. JQM library

    I guess the bind/initialization matters, not sure why. Hope this helps someone.

    ReplyDelete
  7. Hello, thanks for the great solution. Do you think if there is a way to display the second banner on the page? One in the header and other (or the same) in the footer.

    ReplyDelete
    Replies
    1. Yes, you can have a second banner. You can use the same technique to put one in the header as well.

      Delete
    2. I have no luck to get the second showed up. The only first one, in the header. I tried to add

      1. <script type="text/javascript"
      src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
      </script> in two places but only in the footer it works.
      2. I tried to add two parts that one from <head></head> to footer, but none of this technique was not working. Any idea? Have you tried to display two ads on the same page? Probably you have code example. I am not sure where I am doing wrong.

      Delete
    3. I will definitely take a look into this, but I have a lot on my plate right now with Code Camp this weekend and my Google+ Hangout on Tuesday. I will try to do a blog post next week about this next week.
      If you solve this before, please let me know.

      Delete
    4. I made temporary fix:

      In the <head>
      <script type="text/javascript">
      google_ad_client = "ca-pub-xxxxxxxxxxxxxxxx";

      google_ad_slot = "xxxxxxxxxxxxxx";
      google_ad_width = 320;
      google_ad_height = 50;

      </script>

      And second just mobile unit, it is being supported by google but won't be soon:

      <script type="text/javascript">


      window.googleAfmcRequest = {
      client: 'ca-mb-pub-xxxxxxxxxxxxxxxx',
      format: '320x50_mb',
      output: 'HTML',
      slotname: 'xxxxxxx',
      };

      </script>



      </head>

      And one code in the header and one in the footer to display ads respectively:
      Header:
      <script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
      </script>

      Footer:
      <script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_afmc_ads.js"></script>

      At least it works for now, but will need to figure out "permanent" fix ))

      Delete
  8. Note on the issue with page transitions and ajax in jQueryMobile, I came across this link that seems to have a newer solution using MoSync (which I have not yet tried):

    http://ciitronian.com/blog/programming/javascript/integrating-inmobi-ads-jquerymobile-mosync-based-app/

    Hope you find this useful.

    ReplyDelete
  9. Can this still be used? I understand that Adsense in Cordova is not allowed anymore by Google.

    Read last paragraph of: http://support.google.com/adsense/bin/answer.py?hl=en&answer=68724

    ReplyDelete
    Replies
    1. Hi JD,

      Thanks for taking the time read my blog. The post is about using AdSense with jQuery Mobile which is just a website which is AdSense's use case. For Cordova, you should use AdMob.

      Delete
  10. Thanks to provides a wide information about the mobile web development.......

    mobile web development

    ReplyDelete
  11. Hello

    Unfortunately I'm unable to get my ads working in my jQuery site ... I get this message from the error console:

    "Unsafe JavaScript attempt to access frame with URL http://googleads.g.doubleclick.net/pagead/html/r20130822/r20130206/zrt_lookup.html#I-http%253A%252F%252Fwww.healthyspiral.com%252Fhealthsearch%252Fsearching.html%2F3444705167%2F1 from frame with URL about:blank. Domains, protocols and ports must match."

    I see that your web app example still works, and I've tried to compare my code with yours, to see what i may be doing wrong ... is there a version of jQuery Mobile that works better, for example?

    I wonder if you would be willing to consult on this, for a fee?
    You can contact me at
    sandrawood@woodsresearch.com

    thanks for any help you can give me
    best regards
    Sandra

    ReplyDelete