Extension to the hit-counter for logging hits to files linked in the quick-start

This is an extension to this solution: http://spjsblog.com/2011/05/28/hit-counter-and-star-rating-for-sharepoint/

I got a request for a solution to add hit counter functionality to a set of custom HTML pages in a document library. While you can add the hit counter code to the page, it will be a bit cumbersome if you have pages not inheriting from the master page.

I will here describe a possible solution to the problem, but this requires you to access these files from a link in for example the quick launch. It will not work if you go to the document library directly and open the file.

The code

Add a web part page to a document library in your site. Add a HTML form web part, or a SCRIPT editor web part to the page, and add this code:

<div style="font-size:25px;color:green;">Please wait while we open the requested page...</div>
<script type="text/javascript" src="/SPJS/DFFS/plugins/jquery.js"></script>
<script type="text/javascript" src="/SPJS/DFFS/plugins/SPJS-utility.js"></script>
<script type="text/javascript">

var hitCounterListName = "HitCounter";
var hitCounterListBaseUrl = "";

function spjs_logHitAndRedirect(){
	var redirTo = GetUrlKeyValue("goto"), res, data = {};	
	if(redirTo !== ""){
		data.Title = "Hit";
		data.URL = unescape(redirTo);
		data.User = (typeof _spUserId !== "undefined" ? _spUserId : _spPageContextInfo.userId);
		data.ReferringURL = document.referrer;
		res = spjs_addItem({
			"listName":hitCounterListName,
			"listBaseUrl":hitCounterListBaseUrl,
			"data":data
		});
		if(!res.success){
			alert(res.errorText);
		}else{
			location.href = redirTo;
		}
	}else{
		alert("Append \"?goto=[url to page] to the URL to log a hit, and redirect to the page.");
	}
}

_spBodyOnLoadFunctions.push(spjs_logHitAndRedirect);
</script>

You must edit the code and add the correct link to jQuery and spjs-utility.js. You must also provide the correct name and path to the HitCounter list in the variables “hitCounterListName” and “hitCounterListBaseUrl”. This should be the same as you use in the “argObj” in the hit counter setup.

How to use

The link to the HTML page you add to the quick start must be on this format:

https://contoso.sharepoint.com/SitePages/ThePageWhereYouPutTheCode.aspx?goto=https://contoso.sharepoint.com/DocumetLibrary/YourFile.html

The above will log a hit on “https://contoso.sharepoint.com/DocumetLibrary/YourFile.html” and redirect you to this file.

Alexander

Leave a Reply