Show Google AdSense based on User’s Device

Posted on November 7, 2017 at 2:49 pm

Let’s say I want to show Google AdSense after the .header class for non-mobile devices (desktops, laptops, etc), and show Google AdSense before a form on mobile devices only.

Here is the jQuery code example:

// Show Google AdSense after the .header if device is not mobile
if (/Mobi/i.test(navigator.userAgent) == false && /Android/i.test(navigator.userAgent) == false ) {
$('.header').after("<div class=\"adsense\"><script async src=\"//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js\"></script><ins class=\"adsbygoogle\" style=\"display:block\" data-ad-client=\"YOUR_PUB_ID_CODE_HERE\" data-ad-slot=\"YOUR_AD_SLOT_NUMBER_HERE\" data-ad-format=\"auto\"></ins><script>(adsbygoogle = window.adsbygoogle || []).push({});</script></div>");
}
 
// Show Google AdSense before the .form if device is mobile
if (/Mobi/i.test(navigator.userAgent) == true || /Android/i.test(navigator.userAgent) == true ) {
$('.form').before("<div class=\"adsense\"><script async src=\"//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js\"></script><ins class=\"adsbygoogle\" style=\"display:block\" data-ad-client=\"YOUR_PUB_ID_CODE_HERE\" data-ad-slot=\"YOUR_AD_SLOT_NUMBER_HERE\" data-ad-format=\"auto\"></ins><script>(adsbygoogle = window.adsbygoogle || []).push({});</script></div>");
}

Other Posts

Updated Posts