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:
- Add the SIL Inline Script macro to the page
- For the output type select None
Paste the following script inside the macro body:
persistent number counter = 0; return "Page view counts: " + counter++;
- 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.
- In the SIL Manager create a new script called isUserAdmin.sil
Paste the following code into the script:Â
return userInGroup("confluence-administrators", currentUserName());
- On the page add a SIL Condition macro to the page
- Edit the macro and add the isUserAdmin.sil script to the script setting
- 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:
- In the SIL Manager create a new script called pageCounter.sil
Paste the following code into the script:Â
persistent number counter = 0; counter++;
Now, got to Confluence Admin > CPRIME TOOLS > SIL Listeners
- Create a new listener by clicking Add Listener
- Add Page View for the Event
- Select the pageCounter.sil file for the SIL Script setting
- 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++; }