Search code examples
google-apps-scriptgoogle-sheetsgoogle-sites

From Google Site manipulate a Google Sheet (as a simpler page visit counter)


I am aware, that I should track my Google Site with Analytics, but I am (for certain reasons) not able to use. Therefore I would like to add a VERY SIMPLE page counter for the Google Site. So for every page displayed, I would like to have a counter in Google Sheets (so add +1). [A plus to display the page counter]

Anyone done this?

Thanks


Solution

  • I don't know how robust this is gonna be you could give it a try

    Option 1: Storing data in Spreadsheet

    It would be very simple to get a cell and sum it on on every request that you get.

    function doGet(e){
      var ss = SpreadsheetApp.getActiveSpreadsheet();
      var sheet = ss.getActiveSheet();
    
      var cellCounter = sheet.getRange(1, 1);
    
      cellCounter.setValue(cellCounter.getValue() + 1);
    
      return HtmlService.createHtmlOutput("<b>current sum is at " + cellCounter.getValue() + "</b>");
    
    }
    

    Option 2: Storing data in script Properties

    Another option is to use the PropertiesService to store the data "inside the script".

    function doGet(e){
      var prop = PropertiesService.getScriptProperties();
    
      var key = "COUNTER";
      var counter = prop.getProperty(key);
    
      if(counter){
        prop.setProperty(key, parseInt(counter) + 1)  
      }else(
        prop.setProperty(key, 1)
      )
    
      return HtmlService.createHtmlOutput("<b>current sum is at " + prop.getProperty(key) + "</b>");
    
    }
    

    Although both options are not very robust, although depending on the traffic you expect it could work very well.