Skip to content

Instantly share code, notes, and snippets.

@sergebat
Last active November 25, 2021 14:23
Show Gist options
  • Save sergebat/a5b7ff349eae0216fe3d20026746275a to your computer and use it in GitHub Desktop.
Save sergebat/a5b7ff349eae0216fe3d20026746275a to your computer and use it in GitHub Desktop.
mraid example
<script src="mraid.js"></script>
<script type="text/javascript">
// Initialize mraid
function initMraid() {
if (!isMraidAvailable()) {
showAd();
return;
}
if (mraid.getState() === "loading") {
console.log("Waiting for the mraid to load");
mraid.addEventListener("ready", onReady);
}
else {
console.log("mraid is ready");
onReady();
}
}
// Called when SDK is ready, we can safely call most of mraid.* functions now
function onReady() {
console.log("onReady");
if (mraid.isViewable()) {
setupAd();
} else {
mraid.addEventListener("viewableChange", onDisplayed);
}
}
// SDK can pre-load ad in the background
// This function is called when the ad is displayed for the end user
function onDisplayed(viewable) {
console.log("onDisplayed: " + viewable);
if (viewable) {
mraid.removeEventListener("viewableChange", onDisplayed);
setupAd();
}
}
// The ad is displayed now, we can setup custom configuration
// (such as orientation lock, custom close button)
function setupAd() {
console.log("setupAd");
// Using custom close button is NOT recommended.
// For maximum compatibility let the player render its own close button
// mraid.useCustomClose(true);
// Ask mraid player to force your ad in a particular orientation
mraid.setOrientationProperties({
allowOrientationChange: false,
forceOrientation: "portrait"
});
showAd();
}
// If mraid object is not available, we should still allow our ad to run
// for testing and demo purposes
function isMraidAvailable() {
return typeof mraid !== "undefined";
}
// Start our ad gameplay logic
function showAd() {
console.log("showAd");
if (isMraidAvailable()) {
document.getElementById("message").innerText = "Ad Started with mraid!";
}
else {
document.getElementById("message").innerText = "Ad Started (no mraid, demo mode)";
}
}
// Close ad
function closeAd() {
console.log("closeAd");
if (isMraidAvailable()) {
mraid.close();
}
}
function cta() {
console.log("Call to action!");
if (isMraidAvailable()) {
mraid.open("http://example.com");
}
}
</script>
<!-- Use absolute urls to your assets -->
<!-- This is a custom close button that you can show/hide -->
<img style="position:absolute; top: 5px; right: 5px" src="https://via.placeholder.com/45x45" onclick="closeAd()">
<img src="https://via.placeholder.com/200x400" onclick="cta()">
<div id="message"></div>
<script type="text/javascript">
initMraid();
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment