How to ignore NULL Value in CRM lookup field? - javascript

I have the following code setup onLoad to generate a banner on a 'Shipment' record whenever the associated Account is marked as "Service Watch". The code currently functions, however it's generating an error alert "unable to get property '0' of undefined or null reference". This error occurs when the user is creating a new Shipment record, as the Account field doesn't have a value yet.
How can I configure the code to ignore a NULL value in the Account field?
function checkServiceWatch() {
try{
var account = Xrm.Page.getAttribute("cmm_account").getValue();
var accountid = account[0].id;
var formattedGuid = accountid.replace("}", "");
accountid = formattedGuid.replace("{", "");
// alert("Accountid: " + accountid); // does that ID have brackets around it?
// alert("Request: " + Xrm.Page.context.getClientUrl() + "/api/data/v8.2/accounts(" + accountid + ")?$select=cmm_servicewatch");
var req = new XMLHttpRequest();
req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.2/accounts(" + accountid + ")?$select=cmm_servicewatch", true);
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.onreadystatechange = function()
{
if (this.readyState === 4)
{
req.onreadystatechange = null;
if (this.status === 200)
{
var result = JSON.parse(this.response);
var serviceWatch = result["cmm_servicewatch"];
// alert("serviceWatch: " + serviceWatch);
if(serviceWatch) //set notification
{
Xrm.Page.ui.setFormNotification("This Account is currently under Service Watch","WARNING","1");
} // else
// {
// //Xrm.Page.ui.clearFormNotification("1");
// }
}
else
{
Xrm.Utility.alertDialog("Status: " + this.status + ", Text: " + this.statusText);
}
}
};
req.send();
}
catch (err) {
alert("ServiceWatchCheckRibbon | checkServiceWatch " + err.message);
}
}
Should ignore records being created, but generate a banner on existing Shipments with Account values.

You have to check that the account variable has been initialised correctly. If it has, returning the variable will be equivalent to true and if it doesn't exist it will return false and not run the rest of the code in the try section. Correct code is below:
function checkServiceWatch() {
try{
var account = Xrm.Page.getAttribute("cmm_account").getValue();
if(account) {
var accountid = account[0].id;
var formattedGuid = accountid.replace("}", "");
accountid = formattedGuid.replace("{", "");
// alert("Accountid: " + accountid); // does that ID have brackets around it?
// alert("Request: " + Xrm.Page.context.getClientUrl() + "/api/data/v8.2/accounts(" + accountid + ")?$select=cmm_servicewatch");
var req = new XMLHttpRequest();
req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.2/accounts(" + accountid + ")?$select=cmm_servicewatch", true);
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.onreadystatechange = function()
{
if (this.readyState === 4)
{
req.onreadystatechange = null;
if (this.status === 200)
{
var result = JSON.parse(this.response);
var serviceWatch = result["cmm_servicewatch"];
// alert("serviceWatch: " + serviceWatch);
if(serviceWatch) //set notification
{
Xrm.Page.ui.setFormNotification("This Account is currently under Service Watch","WARNING","1");
} // else
// {
// //Xrm.Page.ui.clearFormNotification("1");
// }
}
else
{
Xrm.Utility.alertDialog("Status: " + this.status + ", Text: " + this.statusText);
}
}
};
req.send();
}
}
catch (err) {
alert("ServiceWatchCheckRibbon | checkServiceWatch " + err.message);
}
}

Assuming that account will hold an array and account id is not 0
You can either use length property to check if the account exist. If Yes then proceed else you can return
var account = Xrm.Page.getAttribute("cmm_account").getValue();
var accountid = account.length && account[0].id;
if(!accountid) return;
this Line will return the id into accountid if exist else returns 0
var accountid = account.length && account[0].id;
you can also add an additional check if you are not sure id exist in first element of account (account[0]) by adding
var accountid = account.length && (account[0] || {}).id;
which will return you undefined if you have elements in your account variable with the absence of key id
Only when account exist accountid variable will hold the account id if not it will have 0 or undefined which can be handled accordingly if you like to proceed or not.
Please let me know if I have solved your problem.

I will be doing like this always. Simply use this to do null check, stop execution & return.
var account = Xrm.Page.getAttribute("cmm_account").getValue();
var accountid;
if(account != null)
accountid = account[0].id.replace("}", "").replace("{", "");
else
return;

Please be aware that Xrm.Page is deprecated and will be replaced by the newer ExecutionContext. More information can be found at https://learn.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/execution-context
I've modified the relevant part of your code to the new ExecutionContext, but you can still use the Xrm.Page library in case you don't want to switch (yet).
function checkServiceWatch(executionContext) {
var formContext = executionContext.getFormContext();
var account = formContext.getAttribute("cmm_account").getValue();
if (!account) {
return;
}
var accountid = account[0].id;
// removed further code for brevity.
}
The if (!account) statement checks whether the account does not have an undefined or null value. The boolean statement works as null and undefined (along with NaN, 0 and empty strings) will resolve to false in a boolean context.

Related

How to Get Attribute Value of XMLHttpRequest in Results

I have the following Microsoft Dynamics related XMLHttpRequest javascript function, and is encountering issue when attemtping to retrieve the entity attributes of the returned records.
The record managed to be created even though the conditions should have blocked it. It is likely that my following statement caused the issue:
var result1 = results.results[0];
alert("result1: " + result1.id); //Not displayed
function DisableInvalidRecordCreation(context) {
var saveEvent = context.getEventArgs();
var idNumber= Xrm.Page.getAttribute("IDNumber").getValue();
var category= Xrm.Page.getAttribute("Category").getValue();
var id = Xrm.Page.data.entity.getId();
var req = new XMLHttpRequest();
req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v9.0/ccc_cases?$select=IDNumber&$filter=IDNumber eq '" + idNumber+ "' and statecode eq 0", false);
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.setRequestHeader("Prefer", "odata.include-annotations=\"*\",odata.maxpagesize=1");
req.onreadystatechange = function () {
if (this.readyState === 4) {
req.onreadystatechange = null;
if (this.status === 200) {
var results = JSON.parse(this.response);
if (results.value.length > 0 && id == "") {
alert(results.value.length); //Displayed as 1
var result1 = results.results[0];
alert("result1: " + result1.id); //Not displayed
for (var i = 0; i < results.entities.length; i++) {
var returned_category= results.entities[i]["Category"];
alert(returned_category); //Not displayed
if (category == 100000003 && returned_category!= 100000003)
{
alert("Invalid record");
saveEvent.preventDefault();
}
}
}
} else {
Xrm.Utility.alertDialog(this.statusText);
}
}
};
req.send();
}
This is happening because in your get request you are selecting only IDNumber field and not the one you desire like Category
req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v9.0/ccc_cases?$select=IDNumber&$filter=IDNumber eq '" + idNumber+ "' and statecode eq 0", false);
Also it should not be var result1 = results.results[0];
rather it should be var result1 =results.value[0]
sample code snippet for reference
if (this.readyState === 4) {
req.onreadystatechange = null;
if (this.status === 200) {
var results = JSON.parse(this.response);
for (var i = 0; i < results.value.length; i++) {
var abc = results.value[i]["abc"];
var xyz = results.value[i]["xyz"];
var pqr = results.value[i]["pqr"];
var pqr_formatted = results.value[i]["pqr#OData.Community.Display.V1.FormattedValue"];
}
} else {
Xrm.Utility.alertDialog(this.statusText);
}
}

JavaScript helps with conditional syntax

I have a function that calls an API (let's call it API-1) to get the song lyrics.
Since this API sometimes can't find a song in its database, I want to call another API (let's call it API-2) to do the same search.
I need to integrate the code of both APIs inside the function, when the first one doesn't get data.
I tell you some very important information:
In API-1 I must force the data to be fetched as XML and the responseType must be 'document'.
API-2 does not require any of the above conditions, the data is parced as JSON and the responseType it supports is 'text', but does not require it to be set, with 'document' it DOES NOT work, it gives error.
Now I will share the function code for API-1 and then I will share the same function code for API-2.
They both work perfect if I test them independently.
The help I am asking for is to integrate API-2 when API-1 does not fetch data.
Code using API-1
this.refreshLyric = function (currentSong, currentArtist) {
var xhr = new XMLHttpRequest;
xhr.open('GET', proxy_URL + api_URL + 'apiv1.asmx/SearchLyricDirect?artist=' + currentArtistE + '&song=' + ucwords(currentSongE), true);
// ONLY FOR THIS XMLHttpRequest responseType must be empty string or 'document'
xhr.responseType = 'document';
// ONLY FOR THIS XMLHttpRequest force the response to be parsed as XML
xhr.overrideMimeType('text/xml');
xhr.onload = function () {
if (xhr.readyState === xhr.DONE && xhr.status === 200) {
var openLyric = document.getElementsByClassName('lyrics')[0];
var lyric = xhr.responseXML.getElementsByTagName('Lyric')[0].innerHTML;
//check if any data was obtained
if (lyric != '') {
document.getElementById('lyric').innerHTML = lyric.replace(/\n/g, '<br />');
openLyric.style.opacity = "1";
openLyric.setAttribute('data-toggle', 'modal');
} else { /////// HERE INTEGRATE API-2 //////
openLyric.style.opacity = "0.3";
openLyric.removeAttribute('data-toggle');
var modalLyric = document.getElementById('modalLyrics');
modalLyric.style.display = "none";
modalLyric.setAttribute('aria-hidden', 'true');
(document.getElementsByClassName('modal-backdrop')[0]) ? document.getElementsByClassName('modal-backdrop')[0].remove(): '';
}
} else {
document.getElementsByClassName('lyrics')[0].style.opacity = "0.3";
document.getElementsByClassName('lyrics')[0].removeAttribute('data-toggle');
}
};
xhr.send();
}
The same code using API-2
this.refreshLyric = function (currentSong, currentArtist) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState === 4 && this.status === 200) {
var data = JSON.parse(this.responseText);
var openLyric = document.getElementsByClassName('lyrics')[0];
var lyric = data.mus[0].text;
//check if any data was obtained
if (lyric != '') {
document.getElementById('lyric').innerHTML = lyric.replace(/\n/g, '<br />');
openLyric.style.opacity = "1";
openLyric.setAttribute('data-toggle', 'modal');
} else {
openLyric.style.opacity = "0.3";
openLyric.removeAttribute('data-toggle');
var modalLyric = document.getElementById('modalLyrics');
modalLyric.style.display = "none";
modalLyric.setAttribute('aria-hidden', 'true');
(document.getElementsByClassName('modal-backdrop')[0]) ? document.getElementsByClassName('modal-backdrop')[0].remove(): '';
}
} else {
document.getElementsByClassName('lyrics')[0].style.opacity = "0.3";
document.getElementsByClassName('lyrics')[0].removeAttribute('data-toggle');
}
}
xhttp.open('GET', 'https://api.vagalume.com.br/search.php?apikey=' + API_KEY + '&art=' + currentArtist + '&mus=' + currentSong.toLowerCase(), true);
xhttp.send()
}
The shared codes are of the SAME function (this.refreshLyric), what has to be integrated is only the XMLHttpRequest API.
In the ELSE of line 23 of API-1 I must integrate the code of API-2.
I have already tried it in several ways but I am presented with syntax problems with the IF - ELSE conditionals and errors with the API-2 which is getting the responseType and the MimeType of API-1.
EDIT
FIXED: When API-1 cannot find the lyric, I have created a new function that calls API-2. refreshLyric2(currentSong, currentArtist); :)
this.refreshLyric = function (currentSong, currentArtist) {
var xhr = new XMLHttpRequest;
xhr.open('GET', proxy_URL + api_URL + 'apiv1.asmx/SearchLyricDirect?artist=' + currentArtistE + '&song=' + ucwords(currentSongE), true);
// ONLY FOR THIS XMLHttpRequest responseType must be empty string or 'document'
xhr.responseType = 'document';
// ONLY FOR THIS XMLHttpRequest force the response to be parsed as XML
xhr.overrideMimeType('text/xml');
xhr.onload = function () {
if (xhr.readyState === xhr.DONE && xhr.status === 200) {
var openLyric = document.getElementsByClassName('lyrics')[0];
var lyric = xhr.responseXML.getElementsByTagName('Lyric')[0].innerHTML;
//check if any data was obtained
if (lyric != '') {
document.getElementById('lyric').innerHTML = lyric.replace(/\n/g, '<br />');
openLyric.style.opacity = "1";
openLyric.setAttribute('data-toggle', 'modal');
} else {
//If lyric was not obtained, we call API-2
refreshLyric2(currentSong, currentArtist);
}
} else {
document.getElementsByClassName('lyrics')[0].style.opacity = "0.3";
document.getElementsByClassName('lyrics')[0].removeAttribute('data-toggle');
}
};
xhr.send();
}
refreshLyric2 = function (currentSong, currentArtist) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState === 4 && this.status === 200) {
var data = JSON.parse(this.responseText);
var openLyric = document.getElementsByClassName('lyrics')[0];
var lyric = data.mus[0].text;
//check if any data was obtained
if (lyric != '') {
document.getElementById('lyric').innerHTML = lyric.replace(/\n/g, '<br />');
openLyric.style.opacity = "1";
openLyric.setAttribute('data-toggle', 'modal');
} else {
openLyric.style.opacity = "0.3";
openLyric.removeAttribute('data-toggle');
var modalLyric = document.getElementById('modalLyrics');
modalLyric.style.display = "none";
modalLyric.setAttribute('aria-hidden', 'true');
(document.getElementsByClassName('modal-backdrop')[0]) ? document.getElementsByClassName('modal-backdrop')[0].remove(): '';
}
} else {
document.getElementsByClassName('lyrics')[0].style.opacity = "0.3";
document.getElementsByClassName('lyrics')[0].removeAttribute('data-toggle');
}
}
xhttp.open('GET', 'https://api.vagalume.com.br/search.php?apikey=' + API_KEY + '&art=' + currentArtist + '&mus=' + currentSong.toLowerCase(), true);
xhttp.send()
}

Dynamics crm rest builder query for many to many relationship

I need to set a contract lookup field in crm based on the account selected and business unit. This is a many to many relationship in crm .The best way i can think to do this is to create 2 querys/api calls (using crm rest builder) to be able to do this based on the criteria. the first query accesses the intersect table (account-contract table)in order to return all contracts based on the account and the seconds needs to further filter the results by looping through all the results from the first query and do a count off all the contracts that match the business unit selected. the issue im having now is that, i used an array to push all the values from the first query to be able to loop in the second one. However the array i created is not reaching the for loop thus the second query is not executing
function populateContractLookup() {
var buisnessUnitId = getFieldValue("hc_businessunit");
var worksiteId = getFieldValue("hc_worksite")[0].id;
worksiteId = stripCurlies(worksiteId);
if (buisnessUnitId != null) {
buisnessUnitId = stripCurlies(buisnessUnitId[0].id);
var condition = "_hc_businessunit_value eq " + buisnessUnitId + " and";
}
else {
condition = "";
}//to be able to count the how many contracts that would hav gotten populated to contract lookup field
var validcontractid;
var contractCount = 0;
var contractArray = [];
//this query gets all contracts based on account
var req = new XMLHttpRequest();
req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.2/hc_account_contractset?$select=contractid&$filter=accountid eq " + worksiteId, true);
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");
req.onreadystatechange = function () {
if (this.readyState === 4) {
req.onreadystatechange = null;
if (this.status === 200) {
var results = JSON.parse(this.response);
// Xrm.Utility.alertDialog(results.value.length);
for (var i = 0; i < results.value.length; i++) {
var contractid = results.value[i]["contractid"];
// Xrm.Utility.alertDialog(contractid);
contractArray.push(contractid);
}
} else {
Xrm.Utility.alertDialog(this.statusText);
}
}// Xrm.Utility.alertDialog(contractArray.length) prints to the screen here
};
req.send();
//query to furthr filter the above query to get all contracts based on the buisness unit
//Xrm.Utility.alertDialog(contractArray.length);//not printing to screen
for (var i = 0; i < contractArray.length; i++) {
Xrm.Utility.alertDialog("were in the loop"); //not reaching this loop
var req = new XMLHttpRequest();
req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.2/contracts?$select=contractid&$filter=contractid eq " + contractArray[i] + " and _hc_businessunit_value eq " + buisnessUnitId, true);
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");
req.onreadystatechange = function () {
if (this.readyState === 4) {
req.onreadystatechange = null;
if (this.status === 200) {
var results = JSON.parse(this.response);
Xrm.Utility.alertDialog(results.value.length);
for (var i = 0; i < results.value.length; i++) {
contractCount++;
}
} else {
Xrm.Utility.alertDialog(this.statusText);
}
}
};
req.send();
}
}
.ANy ideas of why i cant access my arrary?
Your first request is asynchronous. The code after your first req.send() is executing immediately, whereas you need the result of your first request to have been returned before any other code executes.
You therefore need to wrap your second request, which is dependent on the result of the first, into a callback function. You then call this callback function in the success callback of your first request.
See this StackOverflow answer for information on callback functions.
As an aside, your second request won't work. You're trying to execute a request once per contract that was retrieved. What you want to do is build your OData filter by iterating over contractArray array and writing '(contractid eq ' + contractArray[i] + ') or' //...
As another aside, consider using a FetchXML aggregate to count records.
Your code might look something like this:
var buisnessUnitId = getFieldValue("hc_businessunit");
var worksiteId = getFieldValue("hc_worksite")[0].id;
function populateContractLookup() {
worksiteId = stripCurlies(worksiteId);
if (buisnessUnitId != null) {
buisnessUnitId = stripCurlies(buisnessUnitId[0].id);
var condition = "_hc_businessunit_value eq " + buisnessUnitId + " and";
}
else {
condition = "";
}//to be able to count the how many contracts that would hav gotten populated to contract lookup field
var validcontractid;
var contractCount = 0;
var contractArray = [];
//this query gets all contracts based on account
var req = new XMLHttpRequest();
req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.2/hc_account_contractset?$select=contractid&$filter=accountid eq " + worksiteId, true);
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");
req.onreadystatechange = function () {
if (this.readyState === 4) {
req.onreadystatechange = null;
if (this.status === 200) {
var results = JSON.parse(this.response);
// Xrm.Utility.alertDialog(results.value.length);
for (var i = 0; i < results.value.length; i++) {
var contractid = results.value[i]["contractid"];
// Xrm.Utility.alertDialog(contractid);
contractArray.push(contractid);
}
// Call your callback function.
countContracts(contractArray);
} else {
Xrm.Utility.alertDialog(this.statusText);
}
}// Xrm.Utility.alertDialog(contractArray.length) prints to the screen here
};
req.send();
}
Your callback function (though as I've mentioned above this needs rewriting):
function countContracts(contractArray) {
for (var i = 0; i < contractArray.length; i++) {
Xrm.Utility.alertDialog("were in the loop"); //not reaching this loop
var req = new XMLHttpRequest();
req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.2/contracts?$select=contractid&$filter=contractid eq " + contractArray[i] + " and _hc_businessunit_value eq " + buisnessUnitId, true);
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");
req.onreadystatechange = function () {
if (this.readyState === 4) {
req.onreadystatechange = null;
if (this.status === 200) {
var results = JSON.parse(this.response);
Xrm.Utility.alertDialog(results.value.length);
for (var i = 0; i < results.value.length; i++) {
contractCount++;
}
} else {
Xrm.Utility.alertDialog(this.statusText);
}
}
};
req.send();
}
}
You can try switching the first call as synchronous by changing the flag like below & the result ll be available immediately before the second call.
req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.2/hc_account_contractset?$select=contractid&$filter=accountid eq " + worksiteId, false);

jquery to javascript converted but not working

my initial code was in jquery + ajax and i tried to write it in javascript but its not working now. Can anyone tell me where's the mistake and why its not showing anything when i run through the server? i checked in the console and there is no error either
my code in JQ
$(document).ready(function(){
findteacher = function() {
var file = "course.php?course="+ $("#course").val();
$.ajax({
type : "GET",
url : file,
datatype : "text",
success : function(response) {
var file2 = response.split(",");
$("#courseInfo").html("The course: " + file2[0] + " Taught by: " + file2[1]);
}
});
}
clear = function() {
$("#courseInfo").html("");
};
$("#course").click(clear);
$("#go").click(findteacher);
});
My code in JS
function findteacher () {
var file = "course.php" + document.getElementById('course');
function callAjax(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById('courseInfo').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", file, true);
xmlhttp.send(null);
var file2 = callAjax.split(",");
document.getElementById('courseInfo').text("The course: " + file2[0] + " Taught by: " + file2[1]);
}
document.getElementById('go').onclick(findteacher)
}
window.onload = findteacher;
You're missing ?course= in file. You're not getting .value of the course element. callAjax.split(",") makes no sense -- callAjax is a function, not a string -- you should be using xmlhttp.responseText.split(",") in the onreadystatechange function. onclick is a property you assign to, not a method, so .onclick(findteacher) should be onclick = findteacher; and you shouldn't do this inside the function, it should be done just once when the page is loaded.
function findteacher () {
var file = "course.php?course=" + document.getElementById('course').value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
var file2 = xmlhttp.responseText.split(",");
document.getElementById('courseInfo').innerHTML = "The course: " + file2[0] + " Taught by: " + file2[1];
}
}
xmlhttp.open("GET", file, true);
xmlhttp.send(null);
}
function clear () {
document.getElementById('courseInfo').innerHTML = '';
}
window.onload = function() {
document.getElementById('go').onclick = findteacher;
document.getElementById('course').onclick = clear;
}

Unexpected end of input error with chrome.tabs.query

I've been struggling with this and have had no luck. I've included the error and most of the context around the block in question.
var successURL = 'https://www.facebook.com/connect/login_success.html';
var userFirstName = ''
var userEmail = ''
function onFacebookLogin(){
if (localStorage.getItem('accessToken')) {
chrome.tabs.query({}, function(tabs) {
for (var i = 0; i < tabs.length; i++) {
if (tabs[i].url.indexOf(successURL) !== -1) {
var params = tabs[i].url.split('#')[1];
var accessToken = params.split('&')[0];
accessToken = accessToken.split('=')[1];
localStorage.setItem('accessToken', accessToken);
chrome.tabs.remove(tabs[i].id);
console.log(accessToken);
pullSecurityToken();
findFacebookName();
}
}
});
}
}
chrome.tabs.onUpdated.addListener(onFacebookLogin);
function pullSecurityToken(){
var pointUrl = "localhost:3000/api/v1/retrieve_token_for/" + localStorage.accessToken + "/" + localStorage.securityToken;
var xhr = new XMLHttpRequest();
xhr.open("GET", pointUrl, true);
alert(JSON.parse(xhr.responseText));
}
var response = ''
function findFacebookName(){
if (localStorage.accessToken) {
var graphUrl = "https://graph.facebook.com/me?access_token=" + localStorage.accessToken;
console.log(graphUrl);
var xhr = new XMLHttpRequest();
xhr.open("GET", graphUrl, true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if(xhr.status == '401'){
alert("Security Token Invalid, please check and try again.");
}
response = JSON.parse(xhr.responseText);
userFirstName = response.first_name
userEmail = response.email
console.log(response);
}
}
}
xhr.send();
}
Here's the error:
Error in response to tabs.query: SyntaxError: Unexpected end of input
at onFacebookLogin (chrome-extension://dapeikoncjikfbmjnpfhemaifpmmgibg/background.js:7:17)
Even if you use a synchronous request, you still need to send it. So add an xhr.send(); after the xhr.open inside pullSecurityToken.
As Felix Kling points out in the comments, the lack of send will directly cause your error, because the responseText property is still an empty string and such a string is not valid JSON whereas "" would be valid JSON.

Categories

Resources