How to publish your HTML5 game on Facebook, using Facebook login, Share and CPMStar ads

If you want to monetize your HTML5 game, Facebook can be a gold mine if you manage to make it viral, as according to the official developer page, every month more than 250 million people play games on Facebook.com and on Facebook-connected devices. I have a couple of games running on Facebook I won’t talk about at the moment, as I want to do how they perform without promotion, but I am going to show you Risky Steps, which is basically the same game I published around a month ago based on Circle Path prototype. The main difference is you can play the game directly on Facebook or directly from the secure server where it’s hosted on. In order to publish your HTML5 game on Facebook, you absolutely need an https page. You can check your hosting provider to see if they feature a secure server plan. Then if you play the game, you will notive three things: 1) There’s a Facebook login option popping up 2) There’s a CPMStar ad. Why did I choose CPMStar? First, because I am using it since I tried it with my LineBall game six years ago. Second, because is the one I like the most among Facebook Certified Ad Providers. 3) There is a “share” button in the bottom of the game which opens a Facebook share popup. Time to show you how to develop all these nice things. This is the content of index.html:
<!DOCTYPE html&gt;
<html&gt;
	<head&gt;
	<meta charset="UTF-8" /&gt;
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" /&gt;
	<title&gt;Risky Steps</title&gt;
	
	<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no, minimal-ui" /&gt;
	<meta name="apple-mobile-web-app-capable" content="yes" /&gt;
	<meta name="apple-mobile-web-app-status-bar-style" content="black" /&gt;
	<link rel="apple-touch-icon" sizes="256x256" href="icon-256.png" /&gt;
	<meta name="HandheldFriendly" content="true" /&gt;
	
	<meta name="mobile-web-app-capable" content="yes" /&gt;
	<link rel="shortcut icon" sizes="256x256" href="icon-256.png" /&gt;

     <style type="text/css"&gt;
		* {
			padding: 0;
			margin: 0;
		}
		body {
			background: #000;
			color: #fff;
			overflow: hidden;
			-ms-touch-action: none;
		}
		canvas {
			touch-action-delay: none;
			touch-action: none;
			-ms-touch-action: none;
		}
          #fbad{
               width:100%;
               height:100%;
               background-color:rgba(0,0,0,0.85);
               text-align:center;
               position:absolute;
               top:0px;
               left:0px;
               z-index:1000;
          }
          #closebutton{
               cursor:pointer;
               background-color:green;
               width:280px;
               margin:50px auto;
               padding:10px;
               font:bold 14px arial;
               color:white;
               text-transform:uppercase;     
          }
	</style&gt;
	<script src="phaser.min.js"&gt;</script&gt;
     <script src = "game.js"&gt;</script&gt;
     <script src = "facebook.js"&gt;</script&gt;
	</head&gt;
	<body&gt;
     <div id = "fbad"&gt;
          <div style = "margin-top:120px"&gt;
               <script language="Javascript"&gt;
                    var cpmstar_rnd=Math.round(Math.random()*999999);
                    var cpmstar_pid=10016;
                    document.writeln("<SCR"+"IPT language='Javascript' src='//server.cpmstar.com/view.aspx?poolid="+cpmstar_pid+"&amp;script=1&amp;rnd="+cpmstar_rnd+"'&gt;</SCR"+"IPT&gt;");
               </script&gt;
          </div&gt;
          <div id = "closebutton" onclick = "removeAd()"&gt;</div&gt;
     </div&gt;
     <script&gt;
          var count = 0;
          adCounter();
          var intervalId = setInterval(adCounter, 1000);
          var canClose = false;
          function removeAd(){
               if(canClose){
                    document.body.removeChild(document.getElementById("fbad"));
               }
          }
          function adCounter() {
               if (count &gt; 9) {
                    clearInterval(intervalId);
                    document.getElementById("closebutton").innerHTML = "Close and and play game";
                    canClose = true;
                    return;
               }
               count ++;
               document.getElementById("closebutton").innerHTML = "Closing ad in " + (10 - count).toString() + " seconds";
          }
     </script&gt;             
	</body&gt;
</html&gt;
As you can see, the whole ad thing is just a javascript counter with a couple of CSS overlays similar to a lightbox. I made it the old way because I did not want to include jQuery. About Facebook stuff, it’s everything in facebook.js file:
var facebookName = "";

window.fbAsyncInit = function() {
     FB.init({
          appId      : "814839665310245",
          xfbml      : true,
          version    : "v2.5"
     });

     FB.getLoginStatus(function(response) {
          if (response.status == "connected") {
               onLogin(response);
          } else {
               FB.login(function(response) {
                    onLogin(response)
               }, {scope: "user_friends, email"});
          }
     });
      
};   

function onLogin(response) {
     if (response.status == "connected") {
          FB.api("/me?fields=first_name", function(data) {
               facebookName = data.first_name;
          });
     }
}

function shareScore(n){
     FB.ui({
          method: "feed",
          link: "https://apps.facebook.com/risky-steps/",
          caption: "Play Risky Steps now!!",
          name: "My best score on Risky steps is " + n + "!!!!",
          description: "I scored " + n + " points on Risky Steps. Can you beat my score?",
          picture: "https://www.feronato.com/facebook/risky-steps/assets/pictures/feedpic.png"
     }, function(response){});
}

(function(d, s, id){
     var js, fjs = d.getElementsByTagName(s)[0];
     if (d.getElementById(id)) {return;}
     js = d.createElement(s); js.id = id;
     js.src = "//connect.facebook.net/en_US/sdk.js";
     fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
Most of the code is the default code you get from Facebook itself when you upload a game, I just made shareScore function (lines 30-39) which is called from the game itself when share button is pressed. The n argument is the best score. facebookName variable is ready to be used although I do not use it yet. Nwxt time, I will show you how to create a leaderboard, and explain more in depth the whole code and monetization strategy

Get the most popular Phaser 3 book

Through 202 pages, 32 source code examples and an Android Studio project you will learn how to build cross platform HTML5 games and create a complete game along the way.

Get the book

214 GAME PROTOTYPES EXPLAINED WITH SOURCE CODE
// 1+2=3
// 100 rounds
// 10000000
// 2 Cars
// 2048
// A Blocky Christmas
// A Jumping Block
// A Life of Logic
// Angry Birds
// Angry Birds Space
// Artillery
// Astro-PANIC!
// Avoider
// Back to Square One
// Ball Game
// Ball vs Ball
// Ball: Revamped
// Balloon Invasion
// BallPusher
// Ballz
// Bar Balance
// Bejeweled
// Biggification
// Block it
// Blockage
// Bloons
// Boids
// Bombuzal
// Boom Dots
// Bouncing Ball
// Bouncing Ball 2
// Bouncy Light
// BoxHead
// Breakout
// Bricks
// Bubble Chaos
// Bubbles 2
// Card Game
// Castle Ramble
// Chronotron
// Circle Chain
// Circle Path
// Circle Race
// Circular endless runner
// Cirplosion
// CLOCKS - The Game
// Color Hit
// Color Jump
// ColorFill
// Columns
// Concentration
// Crossy Road
// Crush the Castle
// Cube Jump
// CubesOut
// Dash N Blast
// Dashy Panda
// Deflection
// Diamond Digger Saga
// Don't touch the spikes
// Dots
// Down The Mountain
// Drag and Match
// Draw Game
// Drop Wizard
// DROP'd
// Dudeski
// Dungeon Raid
// Educational Game
// Elasticity
// Endless Runner
// Erase Box
// Eskiv
// Farm Heroes Saga
// Filler
// Flappy Bird
// Fling
// Flipping Legend
// Floaty Light
// Fuse Ballz
// GearTaker
// Gem Sweeper
// Globe
// Goat Rider
// Gold Miner
// Grindstone
// GuessNext
// Helicopter
// Hero Emblems
// Hero Slide
// Hexagonal Tiles
// HookPod
// Hop Hop Hop Underwater
// Horizontal Endless Runner
// Hundreds
// Hungry Hero
// Hurry it's Christmas
// InkTd
// Iromeku
// Jet Set Willy
// Jigsaw Game
// Knife Hit
// Knightfall
// Legends of Runeterra
// Lep's World
// Line Rider
// Lumines
// Magick
// MagOrMin
// Mass Attack
// Math Game
// Maze
// Meeblings
// Memdot
// Metro Siberia Underground
// Mike Dangers
// Mikey Hooks
// Nano War
// Nodes
// o:anquan
// One Button Game
// One Tap RPG
// Ononmin
// Pacco
// Perfect Square!
// Perfectionism
// Phyballs
// Pixel Purge
// PixelField
// Planet Revenge
// Plants Vs Zombies
// Platform
// Platform game
// Plus+Plus
// Pocket Snap
// Poker
// Pool
// Pop the Lock
// Pop to Save
// Poux
// Pudi
// Pumpkin Story
// Puppet Bird
// Pyramids of Ra
// qomp
// Quick Switch
// Racing
// Radical
// Rebuild Chile
// Renju
// Rise Above
// Risky Road
// Roguelike
// Roly Poly
// Run Around
// Rush Hour
// SameGame
// SamePhysics
// Save the Totem
// Security
// Serious Scramblers
// Shrink it
// Sling
// Slingy
// Snowflakes
// Sokoban
// Space Checkers
// Space is Key
// Spellfall
// Spinny Gun
// Splitter
// Spring Ninja
// Sproing
// Stabilize!
// Stack
// Stick Hero
// String Avoider
// Stringy
// Sudoku
// Super Mario Bros
// Surfingers
// Survival Horror
// Talesworth Adventure
// Tetris
// The Impossible Line
// The Moops - Combos of Joy
// The Next Arrow
// Threes
// Tic Tac Toe
// Timberman
// Tiny Wings
// Tipsy Tower
// Toony
// Totem Destroyer
// Tower Defense
// Trick Shot
// Tunnelball
// Turn
// Turnellio
// TwinSpin
// vvvvvv
// Warp Shift
// Way of an Idea
// Whack a Creep
// Wheel of Fortune
// Where's my Water
// Wish Upon a Star
// Word Game
// Wordle
// Worms
// Yanga
// Yeah Bunny
// Zhed
// zNumbers