Get All File Versions in SharePoint using JSOM

The example in this topic show how to use JSOM to Get All File Versions in SharePoint

  • var oItems, clientContext, oFile, oFileVersions;
  • function GetAllVersions() {
  •     // You can optionally specify the Site URL here to get the context
  •     // If you don't specify the URL, the method will get the context of the current site
  •     // var clientContext = new SP.ClientContext("http://MyServer/sites/SiteCollection");
  •     clientContext = new SP.ClientContext();
  •  
  •     // Get List Object
  •     var olistCollection = clientContext.get_web().get_lists();
  •     var oList = olistCollection.getByTitle("Documents");
  •  
  •     // Get Item using CAML Query
  •     var camlQuery = new SP.CamlQuery();
  •     camlQuery.set_viewXml('<View><Query><Where><Eq><FieldRef Name=\'FileLeafRef\'/>' + '<Value Type=\'File\'>Document.docx</Value></Eq></Where></Query></View>');
  •     oItems = oList.getItems(camlQuery);
  •  
  •     // Load List Item collection object
  •     clientContext.load(oItems);
  •  
  •     // Execute the query to the server.
  •     clientContext.executeQueryAsync(onsuccess, onfailed);
  • }
  •  
  • function onsuccess() {
  •     // Loop through each Item.
  •     var itemCount = oItems.get_count();
  •     for (var i = 0; i <= itemCount - 1; i++) {
  •         // Get File object of the list item
  •         oFile = oItems.itemAt(i).get_file();
  •         oFileVersions = oFile.get_versions();
  •         clientContext.load(oFileVersions);
  •  
  •         break;
  •     }
  •  
  •     //Execute the batch
  •     clientContext.executeQueryAsync(FinalQuerySuccess, FinalQueryFailure);
  • }
  •  
  • function onfailed(sender, args) {
  •     console.log('Failed' + args.get_message() + '\n' + args.get_stackTrace());
  • }
  •  
  • function FinalQuerySuccess(sender, args) {
  •  
  •     // Iterate through Enumerator
  •     var oEnumerator = oFileVersions.getEnumerator();
  •     while (oEnumerator.moveNext()) {
  •         var oFile = oEnumerator.get_current();
  •         console.log("Version Label : " + oFile.get_versionLabel());
  •         console.log("Version Comment : " + oFile.get_checkInComment());
  •     }
  • }
  •  
  • function FinalQueryFailure(sender, args) {
  •     console.log('Failed' + args.get_message() + '\n' + args.get_stackTrace());
  • }

Thank you for reading this article. This code was tested in SharePoint 2013


© 2019 Code SharePoint