You can write some simple JSOM script to achieve this functionality. Since you are using SP 2013 , you can leverage Search service to get the number of visits for any page.
- In a Javascript file , write a method which use KeywordQuery to query for the current page and retrieve the ViewsLifeTime property value and dump this value in some UI element in the masterpage.(Put this js file in style library)
- Reference this Javscript file in the masterpage.
Below is the sample code for same:
var context;
var web;
var list;
var currentItem;
$(document).ready(function () {
//Make sure sp.js ,sp.runtime.js and sp.search.js are loaded
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function () {
SP.SOD.executeFunc("SP.Search.js", "Microsoft.SharePoint.Client.Search.Query.KeywordQuery", LoadCurrentPageID);
});
});
function LoadCurrentPageID()
{
context = new SP.ClientContext.get_current();
web = context.get_web();
list = web.get_lists().getById(_spPageContextInfo.pageListId);
currentItem = list.getItemById(_spPageContextInfo.pageItemId);
context.load(currentItem);
context.executeQueryAsync(onQuerySucceeded, onQueryFailed);
}
//Get the page guid and perform a keyword query such that only the current page is returned.
function onQuerySucceeded() {
var keywordQuery = new Microsoft.SharePoint.Client.Search.Query.KeywordQuery(context);
keywordQuery.set_queryText('PageGuid:"{' + currentItem.get_fieldValues("UniqueId").UniqueId.toString() + '}"');
var searchExecutor = new Microsoft.SharePoint.Client.Search.Query.SearchExecutor(context);
results = searchExecutor.executeQuery(keywordQuery);
context.executeQueryAsync(SearchDone, SearchFailed)
}
function onQueryFailed(sender, args) {
//Error Logging
console.log(args);
}
function SearchDone() {
var viewCount = results.m_value.ResultTables[0].ResultRows[0].ViewsLifeTime;
//Dump the view count onto the UI element in the page
$('#spanViewCount').text(viewCount);
}
function SearchFailed(sender, args) {
//Error Logging
console.log(args);
}
Prerequisites:
- Make sure Search is configured with continuous crawl.
- Load sp.js,sp.runtime.js and sp.search.js in the page