Home Developer FAQ

Developer FAQ

By Tan Tran
16 articles

Customize HTML5 Engine Games With Code?

There is limited interaction a user can have with the HTML5 engine. This is and advanced feature, so our support team may not be able to help you quickly. Before using these features or reaching out to our support team, please make sure you have an intermediate to advanced understanding of javascript and how it works in the browser. The most comprehensive example of how to uses these types of features lives in the sample-legendsoflearning.html file included with your HTML5 package. Change Engine State The following functions are available: gse.pauseGame(); // Pauses the Game gse.playGame(); // Resumes the Game gse.resetGame(); // Resets the Game gse.getGameVolume(); // Gets the engine volume You can also write functionality to control the volume of the game inside the gse.ready callback.  Inside that callback you can call the following two functions: gse.setGameVolume(engine, volume[0-1]); // Sets the volume for the whole game. Must be called where the engine context is available. This can be hooked up in the gse.ready callbackback function.  This must happen inside the gse.ready callback, because you can only set the volume after the engine has initialized. Handle Engine Events via Delegates On the sample-index.html file provide, inside the gse.ready callback function, you will see a playerDelegate object which has 3 delegate functions defined. These two actually trigger on engine events: Life Cycle Delegates onLoadingBegin: function() // define what you want to happen while the engine is loading a scene onLoadingEnd: function() // define what you want to happen when the engine is done loading a scene onCurrentSceneChanged: function(sceneKey, scenename) // define what extra actions to take when the scene changes. good for analytics or ads onSceneAboutToChange: function (sceneKey, sceneName, adType) // lets you know before a scene changes. good for analytics or ads onEndGame: function() // Called when the end game behavior is triggered. External Behavior Delegates onShowBannerShow: function(position[‘top’|’bottom’]) // Triggered by the Show Banner Ad Action. Use this to trigger code to show ads. onTweetSheet: function(message, image) // Triggered by Tweet Sheet Action. One of the most flexible delegates, can be used to trigger almost anything based on the values of the message and image fields. onLogDebuggingStatement: function (text, entity) // Called when log Debug Statement action is triggered. IAP Delegates onIAPBuyItem: function (itemInfo) //  itemInfo: {itemID, consumable, name, price, state}. Return a promise that rejects if the purchase fails and resolves with the following json object: {buyerCancelled: (true || false), purchaseComplete: (true || false)}. onIAPRestoreItems: function () // Returns a promise. Resolves with purchases object. Purchases is an array of objects containing the key itemID for all items purchased. onIAPConsumeItem: function (itemInfo) // itemInfo: {itemID, consumable, name, price, state}. Return a promise that rejects if the purchase fails and resolves if the purchase is a success. onIAPRequestPurchaseData() // Promise that resolves successful with itemInfo (see onIAPBuyItem) or rejects unsuccessfully. Game Service Delegates onGameCenterLogin: function () // Called when Game Service Login is triggered. Return a promise. If resolve is called, Platform Connected will be set to true. onGameCenterPostScore: function (score, leaderboard) // No promise, just do what you will with the score and leaderboard name. onGameCenterShowAchievements: function () // Called when the Show Achievements action is triggered. onGameCenterResetAchievements: function () // Called when the Reset Achievements action is triggered. onGameCenterUpdateAchievement: function (identifier, percentageComplete) // Called when Update Achievement is called. onGameCenterShowLeaderboard: function (identifier) // Called when Show Leaderboard action is triggered. Data Loading Delegates onSaveTable: function(key, table, defaultFunction) { // Intercept save table events. If your delegate returns anything but undefined, the default table saving behavior will be skipped. You can use this to do things in addition to saving table data to local storage, or you can override storing the table to store the data elsewhere like a server. onSaveAttribute: function(key, value, defaultFunction) { // Intercept save attribute events. If your delegate returns anything but undefined, the default attribute saving behavior will be skipped. You can use this to do things in addition to saving attributes to local storage, or you can override storing the attribute to store the data elsewhere like a server. onLoadAttribute: function(key, defaultFunction) { // Intercept load attribute events. If your delegate returns anything but undefined, the default attribute saving behavior will be skipped. You can use this to do things in addition to saving attributes to local storage, or you can override storing the attribute to store the data elsewhere like a server. Posting Events to Engine You can also post events to the engine from inside the delegates. This will let you change attributes which can trigger events in your game logic. You will need to define this inside the gse.ready function in your index page, so you have access to the engine object. These require a bit more advanced knowledge about the internals of how some things work in the engine, so please consult a knowledgable member of our forums or our support team before using them. To post an event you will call postEvent on the engine object. engine.postEvent(event, null, param1, param) Events Include: localeDetected – param1 is the location code, param2 is the language code. Use this if you are using something other than browser information to detect a users locale information (like a call to an external API or an event from another javascript library). giveAdReward – param1 reward name, param2 reward value. Use this to update ad rewards from the results of your ad display in onCurrentSceneChanged or onShowBannerShow externalWriteGameAttribute – param1: attribute path, param2 value. Use this to update an attribute. You will need to provide the full attribute path so something like ‘game.attributes.name’ or the actual internal attribute Id for custom attributes like ‘game.attributes.id12345’. For the value you can provide a simple value like a string or number. You can also update a table (assuming your attribute is a table) by providing the complete table JSON structure (the same structure sent and received via the network behaviors). loadExternalImage – param1 imageId, param2 url. You can use this to replace an existing image in your game project with an image loaded from a URL. The imageId is the name of your image in your project. The URL is the url for the new image. If the image is already on display, call this will replace the image once it has finished loading from the network. If the URL is unable to load an image, the original image from the game project will continue to display.

Last updated on Jul 07, 2025

How Do I Use The Javascript Delegate System For HTML5 Games?

Engine Startup Life Cycle GameSalad has a delegate system that will allow you to hook into certain events in the GameSalad Engine. When GameSalad is done loading the engine, it calls the global (or window) function onEngineLoad. window.onEngineLoad = function () { } At this point you have access to the global variable gse (GameSalad Engine). This isn’t an instance of the engine, but a point of access to the engine. The next thing to happen is that you can register a callback function that is run when the engine is “Ready”.  You can do this by calling the gse.ready() method and passing a callback function. The argument to this callback function IS the actual engine instance that is running the game. window.onEngineLoad = function () {         gse.ready(function (engine) { // Environment specific init code goes here. }); } Now let’s look at this engine instance. In default-index.html you will see a lot of code inside the ready callback. All this code does stuff that is specific to the platform (because the HTML5 engine is used in more than just websites, the code here can look different). Here are the basics of what’s usually in there. window.onEngineLoad = function () {         gse.ready(function (engine) { // Environment specific init code goes here. engine.setRenderFrame('gse-player'); // The ID of the DIV that will contain where the game renders. // Options for how the engine tries to adjust the window size and how it renders. engine.setOptions({ 'viewport-reference': 'window', 'Viewport-fit’: 'letterbox'                          }); // This loads any options passed as query parameters. You can usually omit this. engine.loadOptionsFromURL(); // This loads the game. engine.load(); }); } Handling Game Events with Delegates Now, let’s look at the delegates. The GameSalad engine object has a method called engine.appendDelegate that takes a HashMap of functions. Possible functions are documented here: https://support.gamesalad.com/support/solutions/articles/42000112581 Here is a minimal implementation that covers what do while the engine is in a “loading” state (i.e. before the game begins or between scenes). window.onEngineLoad = function () {         gse.ready(function (engine) {                 // Define delegates                 // Get a reference to a div that shows a loading indicator.                 var loadingElement = document.getElementById('gse-loading');                 const playerDelegate = {                         onLoadingBegin: function() {               console.log("Loading begin.");                               engine.showOverlay(); // Signals engine to show the internal loading indicator.                       loadingElement.style.visibility = 'visible'; // Make our own overlay visible.                     },                     onLoadingEnd: function() {                            loadingElement.style.visibility = 'hidden'; // Hide our own overlay               engine.hideOverlay(); // Signals the engine show the internal loading indicator. } } engine.appendDelegate(playerDelegate) // Environment specific init code goes here. engine.setRenderFrame('gse-player'); // The ID of the DIV that will contain where the game renders. // Options for how the engine tries to adjust the window size and how it renders. engine.setOptions({ 'viewport-reference': 'window', 'Viewport-fit’: 'letterbox'                  }); engine.loadOptionsFromURL(); // This loads any options passed as query parameters. You can usually omit this. engine.load() // This loads the game. }); } To handle more functions, you add functions that match the spec in our doc to the player delegate. Writing Values To Engine with postEvent Finally, how to send information INTO the engine. The engine has a postEvent method, which lets you tell the engine certain things have happened. You can use two events: 'externalWriteGameAttribute' and 'loadExternalImage' For ‘externalWriteGameAttribute’ the postEvent arguments are as follows: engine.postEvent('externalWriteGameAttribute', null, , value) is a string that tells the engine what attribute to set. You can only set game level attributes and for custom attributes (attributes you create), you will need to know the internal ID of the attribute. You can find this by hovering over the name of the attribute in Creator 2. For image replacement you will call it as follows: engine.postEvent('loadExternalImage', null, , url); loadExternalImage only replaces existing images in the engine. is a string with the name of the image that you see in the Creator image library.  The URL is a string with the URL of the image. Example: Ad Network Support A common request is how to allow GameSalad to use different ad networks as part of a web arcade. We’ll use Lagged SDK as an example, because that’s one of Google Adsens’s partners. First you’ll need to load the ad library, so we’ll need to add something like this in our sample-index.html / index.html file inside the block: Next we’ll want to implement a delegate to actually show the interstitial or rewarded ad: window.onEngineLoad = function() {     // This initializes the LaggedAPI with your own keys.     LaggedAPI.init('YOU_DEV_ID', 'YOUR_PUBLISHER_ID');     // We're going to ask Lagged if there are reward ads available and tell it what to do when the ads are displayed.     // When Lagged figures out if ads are available it will return ad availability and a function to show the ad.     // We'll want to store the function to show ads later.     let showRewardAds = null;     function onRewardAdAvailable(adsAvailable, showAdFunc) {         // No ads available, let's null out the function.         if (!adsAvailable) {             showRewardAds = null;             return;         }         // Set up a function to display ads         showRewardAds = function() {             // Pause the game             gse.pauseGame();             // Show ads using Lagged's ad function             showAdsFunc();         }     }     // This handles the response when the ad is complete.     function onRewardAdComplete(rewardUser) {         // Check if the user should get the reward         if (rewardUser) {             // Set the gamesalad adReward attributes             engine.postEvent('externalWriteGameAttribute', null, 'game.attributes.adReward.name', 'Reward Ad');             engine.postEvent('externalWriteGameAttribute', null, 'game.attributes.adReward.value', 10); // Adjust this to your actual reward.         }         // Check to make sure we have another ad available.         LaggedAPI.GEvents.reward(onRewardAdAvailable, onRewardAdComplete);         // Resume the game.         gse.playGame();     }     // Grab ad availability for the first time:     LaggedAPI.GEvents.reward(onRewardAdAvailable, onRewardAdComplete);     gse.ready(function(engine) {             // Define delegates             // Get a reference to a div that shows a loading indicator.             var loadingElement = document.getElementById('gse-loading');             const playerDelegate = {                 onLoadingBegin: function() {                     console.log("Loading begin.");                     engine.showOverlay(); // Signals engine to show the internal loading indicator.                     loadingElement.style.visibility = 'visible'; // Make our own overlay visible.                 },                 onLoadingEnd: function() {                     loadingElement.style.visibility = 'hidden'; // Hide our own overlay                     engine.hideOverlay(); // Signals the engine show the internal loading indicator.                 },                 onSceneAboutToChange: function(sceneKey, sceneName, adType)) {                   if (adType === 1) {                     // Display interstitial                     gse.pauseGame();                     LaggedAPI.APIAds.show(function() {                         // Resume game when done.                         gse.playGame();                     });                 } else if (adType === 2) {                     // Display rewarded ads if available                     if (showRewardAds != null) {                         showRewardAds();                     }                 }             }         }         engine.appendDelegate(playerDelegate)         // Environment specific init code goes here.         engine.setRenderFrame('gse-player'); // The ID of the DIV that will contain where the game renders.         // Options for how the engine tries to adjust the window size and how it renders.         engine.setOptions({             'viewport-reference': 'window',             'Viewport-fit': 'letterbox'         });         engine.loadOptionsFromURL(); // This loads any options passed as query parameters. You can usually omit this.         engine.load() // This loads the game.     }); }

Last updated on Jul 07, 2025