Wednesday, February 13, 2013

Simple Chrome extension: show a counter from API

I already talked about my game "Blind Friends" (which also exists on Windows Phone)...

The game was not a great success but the number of registered players in my database increases progressively.
I had already created a simple action that sends the number of registered players (in JSON: so I can add more information if I need it):


   1:  public JsonResult playercount()
   2:  {
   3:      return Json(new { Count = Db.GetCountPlayers() }, JsonRequestBehavior.AllowGet);
   4:  }

At the beginning, I was checking that number at the URL corresponding to the action in my web app... But it was not very convenient... So I decided to create a small extension for Chrome:


The code is very simple: I just need to check an URL every two minutes.
The extension contains 4 files:

  • background.js
  • icon.png (I took the favicon of my web app)
  • jquery.js (a local copy of a recent version of Jquery)
  • manifest.json

Code of background.js:


   1:  var pollInterval = 2;  // 2 minutes
   2:   
   3:  function updateCounter() {
   4:      $.getJSON('{the url which returns a json with a "Count" property...}', function(json) {
   5:          chrome.browserAction.setBadgeText({
   6:              text: json.Count.toString()
   7:          });
   8:      });
   9:  }
  10:   
  11:  $(document).ready(function () {
  12:      updateCounter(); // we call the function one time here because
  13:                       // the alarm will be triggered one minute after
  14:   
  15:      chrome.browserAction.setBadgeBackgroundColor({
  16:          color: "#000"
  17:      })
  18:          
  19:      chrome.alarms.onAlarm.addListener(function (alarm) {
  20:          updateCounter();
  21:      });
  22:          
  23:      chrome.alarms.create('blindFriendsAlarm', {periodInMinutes: pollInterval});
  24:  })

Code of manifest.json:


   1:  {
   2:    "manifest_version": 2,
   3:   
   4:    "name": "Blind Friends Counter",
   5:    "description": "Count the number of Blind Friends users.",
   6:    "version": "1.0",
   7:   
   8:    "permissions": [
   9:      "https://www.blindfriendsthegame.com/",
  10:      "alarms"
  11:    ],
  12:    "browser_action": {
  13:      "default_icon": "icon.png"
  14:    },
  15:    "background": {
  16:      "scripts": ["jquery.js", "background.js"],
  17:      "persistent": false
  18:    }
  19:  }

The installation is simple: you have to click on "Load unpacked extension" in the extensions page of Chrome


And you just have to select the folder which contains the previous files...

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.