Access SharePoint Online using Javascript

Thanks SHANTHA KUMAR for his really nice post: http://www.ktskumar.com/2017/01/access-sharepoint-online-using-postman/

What I need here is just convert it to using Javascript:

function connectingToSP() {
(function () {
var cors_api_host = ‘cors-anywhere.herokuapp.com’;
var cors_api_url = ‘https://’ + cors_api_host + ‘/’;
var slice = [].slice;
var origin = window.location.protocol + ‘//’ + window.location.host;
var open = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function () {
var args = slice.call(arguments);
var targetOrigin = /^https?:\/\/([^\/]+)/i.exec(args[1]);
if (targetOrigin && targetOrigin[0].toLowerCase() !== origin &&
targetOrigin[1] !== cors_api_host) {
args[1] = cors_api_url + args[1];
}
return open.apply(this, args);
};
})();

var spURL = “https://ideasportal.sharepoint.com”;

function getWWWAuthentication() {
var dfd = $.Deferred();

$.ajax({
url: spURL,
data: null,
type: “GET”,
beforeSend: function (xhr) { xhr.setRequestHeader(‘Authorization’, ‘Bearer’); },
success: function () {
dfd.resolve(“ERROR”);
},
error: function (jqXHR, status) {
dfd.resolve(jqXHR.getResponseHeader(“www-authenticate”));
}
});

return dfd.promise();
}

function generateAccessToken(wwwAuthenticate) {
var dfd = $.Deferred();

if (wwwAuthenticate.indexOf(“realm”) >= 0) {
var wwwAuthenticateInfo = wwwAuthenticate.split(“,”);
var realm = wwwAuthenticateInfo[0].split(“=”)[1].replace(‘”‘, ”).replace(‘”‘, ”);
var client_id = wwwAuthenticateInfo[1].split(“=”)[1].replace(‘”‘, ”).replace(‘”‘, ”);

var appClientId = “6982a6e1-4df4-48e1-a745-94ba99bd4901”;
var appClientSecret = “2Oz3HMthr+hzi9gTFgIZTv3Fwe+Y9n/L8VUg1XzOCIk=”;

var tenantId = realm;
var grant_type = “client_credentials”;
var newClientId = appClientId + “@” + tenantId;
var client_secret = appClientSecret;
var resource = client_id + “/” + spURL.replace(“https://”, “”) + “@” + tenantId;

var details = {
‘grant_type’: grant_type,
‘client_id’: newClientId,
‘client_secret’: client_secret,
‘resource’: resource
};

var formBody = [];
for (var property in details) {
var encodedKey = encodeURIComponent(property);
var encodedValue = encodeURIComponent(details[property]);
formBody.push(encodedKey + “=” + encodedValue);
}
var strFormBody = formBody.join(“&”);

$.ajax({
url: “https://accounts.accesscontrol.windows.net/” + tenantId + “/tokens/OAuth/2”,
type: “POST”,
headers: {
‘Accept’: ‘application/json’,
‘Content-Type’: ‘application/x-www-form-urlencoded’
},
data: strFormBody,
processData: false,
success: function (response) {
var authorizationToken = response.token_type + ” ” + response.access_token;
dfd.resolve(authorizationToken);
},
error: function (jqXHR, status) {
dfd.resolve(“ERROR”);
}
});

} else {
dfd.resolve(“ERROR”);
}

return dfd.promise();
}

function accessSPResource(authorizationToken) {
var dfd = $.Deferred();

$.ajax({
url: spURL + “/_api/web?$select=Title”,
data: null,
type: “POST”,
beforeSend: function (xhr) {
xhr.setRequestHeader(‘Accept’, ‘application/json;odata=verbose’);
xhr.setRequestHeader(‘Authorization’, authorizationToken);
},
success: function (spResponse) {
dfd.resolve(spResponse.d);
},
error: function (jqXHR, status) {
dfd.resolve(“ERROR”);
}
});

return dfd.promise();
}

function handleSPResource(spResponse) {
console.log(spResponse.Title);
}

getWWWAuthentication()
.then(generateAccessToken)
.then(accessSPResource)
.then(handleSPResource);
}

connectingToSP();