Jenkins REST API call to list active jobs

Posted on September 5th, 2015 at 11:00 AM



 
Make a XMLHTTPRequest (XHR) from a page located in the userContent folder to avoid crosss-origin resource sharing (CORS) conflict. Your html page used to make the API call needs a div placeholder, in this case id="appendToList". Add javscript below (and jquery) to your html page, say list-jobs.html, and save in /var/lib/jenkins/userContent on Jenkins server. Call the XHR request function from window.onload or another event. Active jobs and their latest BUILD NUMBER are listed by calling URL http://%JENKINS-SERVER%:8080/userContent/list-jobs.html where %JENKINS-SERVER% is your server location.

var xmlhttp = false;

function request() 
{
  // make rest call to jenkins
  xmlhttp = false;  
  xmlhttp = new XMLHttpRequest();   // ok for latest IE, Chrome, Firefox and Safari

  xmlhttp.onreadystatechange = handleStateChange;
  var server = "http://%JENKINS-SERVER%:8080"; // substitute %JENKINS-SERVER%
  var xpath = "xpath=//url | //fullDisplayName&wrapper=builds";
  var query = "computer[executors[currentExecutable[*]],oneOffExecutors[currentExecutable[*]]]&" 
  var url = server + "/computer/api/xml?tree=" + query + xpath;
  
  xmlhttp.open("GET",url,true);   // async call
  xmlhttp.onreadystatechange = handleStateChange;     
  xmlhttp.send(null);
}

var handleResponse = function (status, response) 
{ 
  xmlDoc = response;
  var serializer = new XMLSerializer ();
  var str = serializer.serializeToString (response);
  var respStr =""; 
  var urls = [];
  urls = xmlDoc.getElementsByTagName("url");
  var jnames = [];
  jnames = xmlDoc.getElementsByTagName("fullDisplayName");  
  var i = 0;
  if (urls.length > 0)
  {
    for (i = 0;i < urls.length;i++)
    { 
      respStr = respStr + "<a href=\"' + urls[i].firstChild.nodeValue + '\" >" + jnames[i].firstChild.nodeValue + "</a><br>";   
    }
  }
  else
  {
    respStr = "No Jobs Running <br>";
  }
    
  // display jobs
  $("#appendToList").html(respStr);
}

var handleStateChange = function () 
{
  switch (xmlhttp.readyState) 
  {
    case 0 : // UNINITIALIZED
    case 1 : // LOADING
    case 2 : // LOADED
    case 3 : // INTERACTIVE
      break;
    case 4 : // COMPLETED
      handleResponse(xmlhttp.status, xmlhttp.responseXML);
      break;
    default: alert("error");
  }
}