Created
November 28, 2018 14:52
-
-
Save codegard1/ccacbf9e6c1f87767fbc089f37900573 to your computer and use it in GitHub Desktop.
Script to log page views in SharePoint. Include this script in the master pages to track user activity
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function main() { | |
console.time("pageview"); | |
SP.SOD.executeFunc("SP.js", "SP.ClientContext", function() { | |
/** | |
* Create a new item in the pageview list at ~/lists/pageviews | |
*/ | |
// Get the querystring | |
var queryString = window.location.href.split("?") | |
? window.location.href.split("?")[1] | |
: ""; | |
// Object with props for the new list item | |
var newItem = { | |
Title: document ? document.title : "No Title", | |
PV_ServerRequestPath: _spPageContextInfo | |
? _spPageContextInfo.serverRequestPath | |
: "", | |
PV_WebTitle: _spPageContextInfo ? _spPageContextInfo.webTitle : "", | |
PV_CurrentUserLogin: _spPageContextInfo | |
? _spPageContextInfo.userLoginName | |
: "", | |
PV_PageId: _spPageContextInfo ? _spPageContextInfo.pageItemId : "", | |
PV_QueryString: queryString ? queryString : "" | |
}; | |
// Announcement | |
console.log(newItem); | |
// Set up to create a new list item | |
var context = new SP.ClientContext.get_current(); | |
var rootWeb = context.get_site().get_rootWeb(); | |
var pageviewList = rootWeb.get_lists().getByTitle("Pageviews"); | |
var itemCreationInfo = new SP.ListItemCreationInformation(); | |
var listItem = pageviewList.addItem(itemCreationInfo); | |
// Set item props from newItem | |
for (var key in newItem) { | |
if (newItem[key]) { | |
console.log(key + " => " + newItem[key]); | |
listItem.set_item(key, newItem[key]); | |
} else { | |
console.log(key + " is empty"); | |
} | |
} | |
// Commit item to the list | |
listItem.update(); | |
context.executeQueryAsync( | |
// on success | |
function() { | |
console.log("Pageview: " + listItem.get_id()); | |
console.timeEnd("pageview"); | |
}, | |
// on fail | |
function(sender, args) { | |
console.log("Error (Pageview): " + args.get_message()); | |
console.timeEnd("pageview"); | |
} | |
); | |
}); | |
} | |
_spBodyOnLoadFunctionNames.push("main"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment