Daily Lucky Numbers:
2
13
20
29
42
43

EhPortal block code for Google Ads

Started by Chen Zhen, October 19, 2024, 06:17:05 PM

Previous topic - Next topic

Chen Zhen

I have found that Google's ad code that is put into the <head> of the HTML page causes some unwanted behavior.
Sometimes form submissions give errors, requiring the user to re-submit the task which can cause some inconvenience.

Here is a PHP block example that puts your Google Ads code in an iframe, separating it from the main page body yet it will still
work as normal.
Be sure to check the options for hiding the title & body of your block code.
There is an option at the onset of the block code to set your unique Google-Ad ID.
// set this variable to your unique Google-Ad ID
// ie. $googleAdCode = 'us-pub-0000000000000000';
$googleAdCode = 'us-pub-0000000000000000';
echo '<iframe sandbox style="visibility: hidden;width: 0px;height: 0px;position: absolute;" id="smf_gdoc" srdoc=\'<!DOCTYPE html><head></head>
<html>
<body>
<div style="display: none;"><span></span></div>
</body>
</html>\'>
</iframe>
<script>
$(document).ready(function() {
var gmeta = $("<meta>", {
name: "google-adsense-account",
content: "' . $googleAdCode . '"
});
var gscript = $("<script>", {
type: "text/javascript",
src: "https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=' . $googleAdCode . '"
});
gscript[0].setAttribute("async", "");
gscript[0].setAttribute("sandbox", "");
$("head", window.frames["smf_gdoc"].document).append(gmeta[0]);
$("head", window.frames["smf_gdoc"].document).append(gscript[0]);
});
</script>';

I advise not to not put the ad code on any pages that have frequent form submissions.
This code should stop any problems in that respect but it might still be prudent to have the block only display on pages that are primarily read only such as the portal page & forum.
For blocks you can opt advanced options & control the area where the block shows on your website.