Integrate Kongregate’s JavaScript API in HTML5 Game to Submit High Score

Though Kongregate’s API can be directly initialized in the main game’s HTML, the better way is to always create a Kongregate’s Shell which is nothing but another HTML file which you refer for running the game in stead of your default game’s HTML file. The Shell file in turn embeds your game’s default HTML file using an iFrame.

Code for Shell HTML can be used from the code snippet below

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>Kongregate Game Shell</title>
    
    <!-- Load the Kongregate Javascript API -->
    <script src='https://cdn1.kongregate.com/javascripts/kongregate_api.js'></script>

    <!-- Give the shell no border/scroll bars and match the Kongregate background color.
         If your game needs scrollbars, you might need to modify these styles -->
    <style type="text/css">
      html{border: none; overflow: hidden; background-color: #333;height: 100%;}
      body{border: none; background-color: #333;margin:0; padding:0;}
    </style>
  </head>

  <body>
    <script type="text/javascript">
      // Called when the API is finished loading
      function onLoadCompleted(){
        // Get a global reference to the kongregate API
        kongregate = kongregateAPI.getAPI();
        
        // Embed the game into the "contentdiv" div, which is defined below. You can also
        // manually create your own iframe, this function is just for convenience.
        kongregateAPI.embedFrame("index.html");
      }
      
      // Begin the process of loading the Kongregate API:
      kongregateAPI.loadAPI(onLoadCompleted);
    </script>
    
    <!-- The div that the game will be placed into. Make sure to set the Width and height properly -->
    <div id="contentdiv" style="top:0px; left:auto; right:auto; width:400px; height:600px; borders:none;">
      <!-- You can manually put your game iframe in here instead of calling embedFrame above if you wish -->
    </div>
  </body>
</html>

You can change index.html to refer to your game’s HTML file name. Also, you need to ensure the width and height is properly set for your game for “contentdiv”.

Define your localStorage as following in a separate js file (for ex storage.js)

	function LocalStorageManager() {
		this.bestScoreKey = "mygame-bestScore";
		var supported = this.localStorageSupported();
		this.storage = supported ? window.localStorage : window.fakeStorage;
	}

	LocalStorageManager.prototype.localStorageSupported = function () {
		var testKey = "test";
		try {
			var storage = window.localStorage;
			storage.setItem(testKey, "1");
			storage.removeItem(testKey);
			return true;
		} catch (error) {
			return false;
		}
	};
	LocalStorageManager.prototype.getBestScore = function () {
		return this.storage.getItem(this.bestScoreKey) || 0;
	};
	LocalStorageManager.prototype.setBestScore = function (score) {
		this.storage.setItem(this.bestScoreKey, score);
	};

Now in the game’s HTML add code as highlighted below

<!DOCTYPE html>
<html>
	<head>
	<title>My Demo Game</title>
	<style type="text/css">
		body{
			background: #000000;
			padding:0px;
			margin:0px;
		}
	</style>
	<script src='https://cdn1.kongregate.com/javascripts/kongregate_api.js'></script>
	<script src="storage.js"></script>
	<script>
	  var storageManager = new LocalStorageManager;
	
      // Get the reference to the Kongregate API from the parent
      var kongregate = parent.kongregate;
       /**  
       * This function checks if the user is logged in. If they are,
       * it submits the high score
       */
      function checkUserAuthenticated(){
        if(!kongregate.services.isGuest()){
			submitScore();
        }
      }
	  
	        /**
       * Called when the submit score button is pressed. Uses the
       * statistics API to submit the given score to the server
       */
      function submitScore(){
        var score = storageManager.getBestScore();
       if(score){
          kongregate.stats.submit("HighScore",score);
        }
      }

	  // Register for the "login" event so we can tell when a user logs in
      kongregate.services.addEventListener("login",checkUserAuthenticated);
      
      // Check to see if the user is already authenticated
      checkUserAuthenticated();
 
    </script>
    <script src = "game.js"></script>
	</head>
	<body>
	<div id="mygame"></div>
	</body>
</html>

High scores should be submitted twice. Once at the completion of game’s stage, whenever high score is achieved. And then second time whenever game is initially loaded so if there was any issue at the time of submitting it first time, we can ensure that it is fixed next time. There is no need to worry about submitting high score each time game is loaded, Kongregate servers have enough capacity to manage this load.

You can call checkUserAuthenticated() method in your game’s code wherever you are updating the high score. Make sure you have updated high score using storageManager before posting it to Kongregate servers since our method is going to read it back from the storageManager itself (You can modify this according to whichever way you seem it fit in your code).

storageManager.setBestScore(score)

You will also notice that high score was submitted using a key “HighScore”. “HighScore” is name of the statistic that you would need to create in your game once your game is uploaded to Kongregate (If you are still wondering, once you upload the game in Kongragate, there is a Statistics API section in upload game page where you can create a statistic and give it a name which can be used later on in the game’s code for submitting the statistic from the game).

Select “Display in leaderboards” if you want to see “HIGH SCORES” tab. This tab will be become visible as soon as first high score is posted from the game to Kongregate’s servers.

This is as simple as it can get to integrate Kongregate’s API for submitting high scores in your HTML5 game.