Friday, January 10, 2014

Gmail Inbox Notification Widget

I wanted to display my Gmail Inbox unread message count on my personal web page on Google Sites, so I made a tiny Google Apps Script widget to do this.



The code turned out very simple.

code.gs:
function doGet() {
  return HtmlService.createTemplateFromFile('page')
    .evaluate()
    .setSandboxMode(HtmlService.SandboxMode.NATIVE);
}

function getInboxUnreadCount() {
  return GmailApp.getInboxUnreadCount();
}

page.html:
<style type="text/css">
#refresh { color: blue; text-decoration: underline; }
#refresh:hover { cursor: pointer; }
</style>

<div id="inbox">
Inbox (<span id="count">...</span>)
<span id="refresh">refresh</span>
</div>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
function check() {
  clearTimeout(check.timer);
  google.script.run
    .withSuccessHandler(function(result) {
      $('#count').text(result);
      $('#inbox').toggleClass('unread', result > 0);
    })
    .getInboxUnreadCount();
  $('#count').text("...");
  check.timer = setTimeout(check, 600000);
}

$(function() {
  check();
  
  $('#refresh').click(check);
});

</script>

The getInboxUnreadCount() function needed to be run from the script editor to grant the needed permissions to the script, after that it worked from my personal home page.

No comments:

Post a Comment