Skip to content

HTML5 (old)

Warning

Please use the new HTML SDK. This one will not be maintained anymore.

Installation

You can install the SDK by including the following script in the head of your game's index.html:

<script src="https://sdk.crazygames.com/crazygames-sdk-v1.js"></script>

The SDK can be retrieved using CrazyGames.CrazySDK.getInstance(). The SDK must be initialized before using it. This is done by calling init() once.

const crazysdk = window.CrazyGames.CrazySDK.getInstance(); // getting the SDK
crazysdk.init(); // initializing the SDK, call as early as possible

Development

The SDK detects whether it is running on CrazyGames.com, or whether it is being used in a development environment. In development advertisements are not available. Instead, an overlay text will be displayed. For other events such as happy time, gameplay start etc. the console output can be consulted.

To simulate the setup used on CrazyGames, download this template. The file sdk.html uses our game loader to display your game. It assumes that index.html contains the html of your game. This lets your game run using the same setup as it would on crazygames.com. You'll just have to browse to localhost:port/sdk.html to see our game loader in action.

Info

When you upload your game we only look at your index.html file, and provide the game loader for you. The sdk.html page will not be used: keep any logic out of that file, and make sure that your index.html does not include the game loader.

Features

Ad breaks

Guidelines for Advertisements

Please be sure to read our advertisement guidelines, since your game will be rejected without any feedback if it doesn't follow them.

Playing an ad break

Ad breaks can be requested using crazysdk.requestAd(). The shortest way to play an ad is using the following code:

const crazysdk = window.CrazyGames.CrazySDK.getInstance();
crazysdk.init();
crazysdk.requestAd();

Ad Types

We support two different types of ad breaks: midgame and rewarded.

Midgame advertisements can happen when a user died, a level has been completed, etc.

Rewarded advertisements can be requested by the user in exchange for a reward (An additional life, a retry when the user died, a bonus starting item, extra starting health, etc.). Rewarded ads should be shown when users explicitly consent to watch an advertisement. By default requestAd() shows a midgame advertisement. requestAd() has an optional argument that indicates the adtype. You can request both types as follows:

crazysdk.requestAd("midgame");
crazysdk.requestAd("rewarded");

Installing Event Listeners

Ad breaks are displayed as an overlay on top of your game. Your game continues running in the background. To ensure that the game does not interfere with the advertisement, your sound must be muted when the ad starts, and turned back on when it has stopped. To do this, you should implement event listeners.

There are three kinds of events:

  • 'adStarted' is emitted when an advertisement starts playing.
  • 'adFinished' is emitted when an advertisement stops playing.
  • 'adError' is emitted when an error has occurred. This event is also emitted when no advertisement is available.

The following code registers event listeners:

crazysdk.addEventListener("adStarted", this.adStarted); // mute sound
crazysdk.addEventListener("adFinished", this.adFinished); // reenable sound, enable ui
crazysdk.addEventListener("adError", this.adError); // reenable sound, enable ui

To ensure that the event listeners are not called when they are no longer needed, event listeners must be removed as well:

crazysdk.removeEventListener("adStarted", this.adStarted);
crazysdk.removeEventListener("adFinished", this.adFinished);
crazysdk.removeEventListener("adError", this.adError);

Full Example

Here is a full example of displaying ads. It is made with Phaser, but is applicable for other HTML5 game frameworks as well.

class GameScene {
  init() {
    const { CrazySDK } = window.CrazyGames;
    this.crazysdk = CrazySDK.getInstance();
    this.crazysdk.init();
    this.adRequested = false;
    this.installListeners();
  }

  preload() {
    this.requestAd();
    // load other assets while ad is playing
  }

  update() {
    if (this.adRequested) {
      /* block UI */
      return;
    }
    /* game logic here */
    if (this.playerWon()) {
      this.gameFinished();
    }
  }

  gameFinished() {
    this.removeListeners();
  }

  installListeners() {
    this.crazysdk.addEventListener("adStarted", this.adStarted);
    this.crazysdk.addEventListener("adError", this.adError);
    this.crazysdk.addEventListener("adFinished", this.adFinished);
  }

  removeListeners() {
    this.crazysdk.removeEventListener("adStarted", this.adStarted);
    this.crazysdk.removeEventListener("adError", this.adError);
    this.crazysdk.removeEventListener("adFinished", this.adFinished);
  }

  requestAd() {
    this.adRequested = true;
    this.crazysdk.requestAd();
  }

  adStarted = () => {
    this.sound.mute = true;
  };

  adError = () => {
    this.sound.mute = false;
    this.adRequested = false;
  };

  adFinished = () => {
    this.sound.mute = false;
    this.adRequested = false;
  };
}

export default GameScene;

Testing

Ad breaks are not always available, especially when visiting localhost. To enforce an advertisement you can append ?testAds=true to your url (e.g. http://localhost/sdk.html?testAds=true). This will display the testing advertisement of Google.

Ad Banners

Our SDK allows you to display ad banners directly into your game.

Getting Started

To begin, you need to have an HTML container of the banner size present on the screen

<div id="banner-container" style="width: 300px; height: 250px"></div>

Info

Make sure to remove or hide the container when a player navigates away from the associated scene to prevent showing ads at an unintended location.

Then you need to make sure that the CrazyGames SDK has been initialized and that you are listening to the “bannerRendered” and “bannerError” events.

const { CrazySDK } = window.CrazyGames;
const crazysdk = CrazySDK.getInstance();
crazysdk.init();
crazysdk.addEventListener("bannerRendered", (event) => {
  console.log(`Banner for container ${event.containerId} has been
    rendered!`);
});
crazysdk.addEventListener("bannerError", (event) => {
  console.log(`Banner render error: ${event.error}`);
});

Standard banners

Standard banners are fixed size banners that you choose according to your container size. Available sizes are:

  • 728x90
  • 300x250
  • 320x50
  • 468x60
  • 320x100

To request one or multiple standard banners use the requestBanner function.

crazysdk.requestBanner([
  {
    containerId: "banner-container",
    size: "300x250",
  },
]);
  • You can display up to two banners of each size at the same time at once (ex: 728x90 and 300x250, two 300x250, ...), we ask you to make a reasonable usage of banners in order not to deteriorate the player’s experience.
  • You can refresh the banner displayed in a container simply by re-executing the banner request. You'll have to wait a minimum of 60 seconds before refreshing a container. You can do a maximum of 60 refreshes per container for a game session.
  • The banner has to be fully inside the game window and not overlapping any UI element.
  • If you want to display multiple banners on a screen, you must request them at the same time:
crazysdk.requestBanner([
  {
    containerId: "banner-container-1",
    size: "300x250",
  },
  {
    containerId: "banner-container-2",
    size: "300x250",
  },
]);

Responsive banners

The responsive banners feature will requests ads that fit into your container, without the need to specify or select a size beforehand. The resulting banners will have one of the following sizes: 970x90, 320x50, 160x600, 336x280, 728x90, 300x600, 468x60, 970x250, 300x250, 250x250 and 120x600. Only banners that fit into your container will be displayed, if your container cannot fit any of these sizes no ad will be rendered. The rendered banner is automatically vertically and horizontally centered into your container.

Info

Your container size must be set to a non-null value:

<div id="responsive-banner-container" style="width: 500px; height: 500px"></div>

To request one or multiple responsive banners use the requestResponsiveBanner function.

crazysdk.requestResponsiveBanner(["responsive-banner-container"]);
  • You can refresh the banner displayed in a container simply by re-executing the banner request. You'll have to wait a minimum of 60 seconds before refreshing a container. You can do a maximum of 60 refreshes per container for a game session.
  • The container has to be fully inside the game window and not overlapping any UI element.
  • If you want to display multiple banners on a screen, you must request them at the same time:
crazysdk.requestResponsiveBanner(["responsive-banner-container-1", "responsive-banner-container-2"]);

Clearing the banners

The SDK provides 2 methods for clearing the banners:

crazysdk.clearBanner("banner-container");
// or
crazysdk.clearAllBanners();

We recommend that you clear the banners after hiding them. Otherwise, when you request new banners again, the old banners may still appear for a fraction of a second, which negatively impacts the user experience.

This feature lets you share the Crazygames version of your game to the players and invite them to join a multiplayer game. You can call inviteLink with a map of parameters that correspond to your game or game room.

const linkToShare = crazysdk.inviteLink({ roomId: 12345 });

You can check for these parameters in the query string of your location which would be appended something like https://[your-game-url]?roomId=12345

const getQueryString = (searchUrl, field) => {
  const search = searchUrl ? searchUrl : window.location.search;
  const searchParams = new URLSearchParams(search);
  return searchParams.get(field);
};
const roomId = getQueryString(window.location.search, "roomId");

Game loading

We provide functions that enable us to track when and how long the loading of your game takes. The sdkGameLoadingStart() function has to be called whenever you start loading your game. The sdkGameLoadingStop() function has to be called when the loading is complete and eventually the gameplay starts.

// Your game starts loading
crazysdk.sdkGameLoadingStart();
// Loading...
crazysdk.sdkGameLoadingStop();
// Next level's assets are loading now
crazysdk.sdkGameLoadingStart();
// Assets are loaded
crazysdk.sdkGameLoadingStop();

Gameplay

We provide functions that enable us to track when and how users are playing your games. These can be used to ensure our site does not perform resource intensive actions while a user is playing. The gameplayStart() function has to be called whenever the player starts playing or resumes playing after a break (menu/loading/achievement screen, game paused, etc.). The gameplayStop() function has to be called on every game break (entering a menu, switching level, pausing the game, ...) don't forget to call gameplayStart() when the gameplay resumes.

// Main menu, user clicks start
crazysdk.gameplayStart();
// Level is over, displaying switching level screen
crazysdk.gameplayStop();
// Next level starts
crazysdk.gameplayStart();
// The player is pausing the game by looking into the menu
crazysdk.gameplayStop();
// The player closes the menu and gets back to the game
crazysdk.gameplayStart();

Happy time

You can call the happytime() function on player achievements, it will possibly adapt the website to celebrate!

Info

Use this feature sparingly, the celebration should remain a special moment.

// Player beats a boss, reaches a high score, etc.
crazysdk.happytime();

// Player finishes a level, gets an item, etc.
// No need to celebrate

Sitelock

We currently do not have a sitelock for plain Javascript games but do recommend building in some protections to avoid your game files getting stolen. One option is to use an obfuscator (e.g.: https://obfuscator.io/) to obfuscate (part of) your game. The domains you should whitelist are the following:

  • *.crazygames.*
  • *.1001juegos.com.

Adblock Detection

We detect whether the user has installed an adblock tool. We pass this information to the developer through the SDK. The adblock detection is executed when init() is called. You will have to implement an event listener on "adblockDetectionExecuted" which is fired when the adblock detection finished running.

function adblockDetection(event) {
  if (event.hasAdblock) {
    console.log("User is using an adblocker");
  } else {
    console.log("User is NOT using an adblocker");
  }
}

const crazysdk = window.CrazyGames.CrazySDK.getInstance();
crazysdk.addEventListener("adblockDetectionExecuted", adblockDetection);
crazysdk.init();

Info

We require games to function even when the user has an adblock. The detection is not foolproof, and it would be very frustrating for a user not running any adblock to get a non-functional game. You can block extra content, such as custom skins, or some levels, to motivate the user to turn off their adblock. Also, keep in mind that turning off the adblock usually requires a page refresh. Make sure that the progress is saved, or the user may just decide to stop playing your game.

User information

We provide some information about the user, they are contained in the userInfo object. Refer to the following code to know more about fields and format. To get the userInfo object you will need to implement an event listener on "initialized". The callback will be invoked when init() is called. If the initialization has already been done, the callback will be invoked right away.

const { CrazySDK } = window.CrazyGames;
const crazysdk = CrazySDK.getInstance();

function sdkInitialized(event) {
  const userInfo = event.userInfo;
  console.log(userInfo);
  /* UserInfo object example
    userInfo: {
        countryCode: "FR", // ISO 3166-1 alpha-2 country code
        // For browser and os, format is the same as https://github.com/faisalman/ua-parser-js
        browser: {
            name: "Chrome",
            version: "87.0.4280.141"
        },
        os: {
            name: "Windows",
            version: "10"
        },
        device: {
            type: "desktop" // possible values: "desktop", "tablet", "mobile"
        }
    }
    */
}

crazysdk.addEventListener("initialized", sdkInitialized);
crazysdk.init();

Disable unwanted page scroll

By default, browsers scroll the page when a user presses spacebar or the arrow keys. Your game should prevent this behavior. You might not notice it in development because your game is taking on the full height of the window. But when your game is embedded on CrazyGames, you’ll need to prevent scroll. You can do so by adding the following code to your game:

window.addEventListener("wheel", (event) => event.preventDefault(), {
  passive: false,
});

window.addEventListener("keydown", (event) => {
  if (["ArrowUp", "ArrowDown", " "].includes(event.key)) {
    event.preventDefault();
  }
});