Create a page view counter

Page counters can be easily created by Power Scripts for Confluence by using the Persistent Variables feature. This feature will save meta data for each page that can be retrieved by a script.

Add counter to a single page

To add a page view counter to a page you can use the SIL Inline Script macro if you only need to add this feature to a few pages:

  1. Add the SIL Inline Script macro to the page
  2. For the output type select None
  3. Paste the following script inside the macro body:

    persistent number counter = 0;
    return "Page view counts: " + counter++;
  4. The end result will look like this:

Here is an example of the working macro:

Hiding the page counter to non-admin users

If you don't want all users to be able to see the page counter you can hide it by using the SIL Condition macro.

  1. In the SIL Manager create a new script called isUserAdmin.sil
  2. Paste the following code into the script: 

    return userInGroup("confluence-administrators", currentUserName());


  3. On the page add a SIL Condition macro to the page
  4. Edit the macro and add the isUserAdmin.sil script to the script setting
  5. Now, drag the SIL Inline Script macro into the body of the SIL Condition macro like this:

Now the page view counter will only be visible to Confluence admins.

Add counter to all pages or a specific space

To add a page counter to all pages we can use the SIL Listener feature to run the counter script every time a page is viewed:

  1. In the SIL Manager create a new script called pageCounter.sil
  2. Paste the following code into the script: 

    persistent number counter = 0;
    counter++;


  3. Now, got to Confluence Admin > CPRIME TOOLS > SIL Listeners

  4. Create a new listener by clicking Add Listener
  5. Add Page View for the Event
  6. Select the pageCounter.sil file for the SIL Script setting
  7. Press Save

Now the pageCounter.sil script will run every time a page is viewed in any space.

Narrowing the scope of the script

To narrow the scope of this script to specific spaces we can modify the script like this:

string [] allowedSpaces = "SPACE1|SPACE2|SPACE3|SPACE4";

if(arrayElementExists(allowedSpaces, space)) {
    persistent number counter = 0;
    counter++;
}

Or, to exclude page counts from internal users you can modify the script like this:

string [] excludedGroups = "confluence-administrators|employees";
persistent number counter = 0;
boolean countUserView = true;

for(string group in excludedGroups) {
    if(userInGroup(group, currentUser()) == true) {
        countUserView = false;
    }
}

if(countUserView == true) {
    counter++;
}