Jquery/JavaScript - Get active URL, split - javascript

Can anyone help me put my three snippets below into one usable script.
1) Get active window URL
2) Strip URL for ID only
3) Concatenate API request to include ID from URL
The below returns my current window URL.
chrome.tabs.query({active: true, currentWindow: true},
function(tabs) {
var tabURL = tabs[0].url;
console.log(tabURL);
});
Example....https://myapi.com/users/PLLFFR6
function test() {
var urlID = tabURL.split("/");
urlID = urlID[urlID.length-1];
}
This splits down https://myapi.com/users/PLLFFR6 and returns only "PLLFFR6"
var authorizationToken = "xxxxxxxxxxxxx";
function myapiRequest(endpoint, options) {
$.ajax($.extend({}, {
type: 'GET',
dataType: "json",
success: function(data) {
$('.Name').html(data.user.name);
$('.Email').html(data.user.email);
$('.Address').html(data.user.teams[0].name);
},
url: "https://api.myapi.com/" + endpoint,
headers: {
"Authorization": "Token token=" + authorizationToken,
"Accept": "application/vnd.myapi+json;version=2"
}
},
options));
}
myapiRequest('/users/' + urlID + '?include%5B%5D=contact_methods&include%5B%5D=teams');
Based on this example myapiRequest should =
**/users/PLLFFR6?include%5B%5D=contact_methods&include%5B%5D=teams**

Something like this should work:
function currentUrl() {
return new Promise(function (resolve) {
chrome.tabs.query({
active: true,
currentWindow: true
}, function(tabs) {
resolve(tabs[0].url)
})
})
}
function userIdfromUrl(url) {
var parts = url.split('/')
return parts[parts.length - 1]
}
function apiRequest(endpoint, options) {
return new Promise(function (resolve) {
$.ajax(
$.extend({}, {
type: 'GET',
dataType: 'json',
success: function(data) {
resolve(data)
},
url: 'https://api.website.com/' + endpoint,
headers: {
Authorization: 'Token token='+authToken,
Accept: 'application/vnd.myapi+json;version=2'
}
}, options)
)
})
}
/* example usage */
currentUrl()
.then(function (url) {
return userIdfromUrl(url)
})
.then(function (userId) {
return apiRequest('users/' + userId + '?include%5B%5D=contact_methods&include%5B%5D=teams')
})
.then(function (data) {
console.log(data.user.name)
console.log(data.user.email)
console.log(data.user.teams[0].name)
})
Note that since you're using chrome.tabs, this will only work as a Chrome extension, not in a browser. You'll also need jQuery loaded (to use $.ajax and $.extend).

Related

Sync issue with iframe in Chrome and Edge

the following script is used to load in a IFRAME a web application.
function openCashier(destination) {
postIsAnonymous(function (data) {
if (data.IsAnonymous) {
window.parent.location.replace('<%= ResolveUrl("~/Popup/login") %>');
} else {
stateReset('showUserBtn');
WCore.OpenTab('cashier');
$("#cashierPopup").addClass(destination);
$("#cashierFrame").attr('src', '<%= ResolveUrl(Routing.GetUrl("Root-TPAutologin")) %>?Destinazione=' + destination);
}
});
}
In Firefox everything works fine, while in Edge and Chrome I get error 404. If I try to load the contents of the IFRAME in a separate browser session everything works.
I tried to edit the javascript as follows, fearing an asynchronism problem:
function openCashier(destination) {
setTimeout(function () {
postIsAnonymous(function (data) {
if (data.IsAnonymous) {
window.parent.location.replace('<%= ResolveUrl("~/Popup/login") %>');
} else {
stateReset('showUserBtn');
WCore.OpenTab('cashier');
$("#cashierPopup").addClass(destination);
$("#cashierFrame").attr('src', '<%= ResolveUrl(Routing.GetUrl("Root-TPAutologin")) %>?Destinazione=' + destination);
}
});
}, 1000 * 20);
}
With this trick the problem is solved with very bad performances.
PostIsAnonymous code is the following :
function postIsAnonymous(successFunc) {
$.ajax({
type: "POST",
url: '?checkIsAnonymous=1',
cache: false,
contentType: "application/x-www-form-urlencoded;charset=ISO-8859-15",
processData: false,
success: successFunc
});
}
Do you have any suggestions to give me to solve the problem in a more
elegant way? Thank you
I solved the problem with the following code.
function openCashier(destination) {
var dest = destination;
sessionManager.isAnonymous()
.then((data) => {
if (data.IsAnonymous) {
window.parent.location.replace('<%= ResolveUrl("~/Popup/login") %>');
}
else {
stateReset('showUserBtn');
WCore.OpenTab('cashier');
$("#cashierPopup").addClass(dest);
$("#cashierFrame").attr('src', '<%= ResolveUrl(Routing.GetUrl("Root-TPAutologin")) %>?Destinazione=' + dest);
}
})
.catch((err) => {
console.error(err);
});
}
var sessionManager = {
isAnonymous: () => {
return new Promise((resolve, reject) => {
$.ajax({
type: "POST",
url: '?checkIsAnonymous=1',
cache: false,
contentType: "application/x-www-form-urlencoded;charset=ISO-8859-15",
processData: false,
success: function (data) {
resolve(data);
},
error: function (data) {
reject(data);
}
});
})
}
}

Function is returning value before running inner actions

Using SharePoint's PreSaveAction() that fires when the Save button is clicked, I am trying to run checks and manipulate fields before the form is saved. If PreSaveAction() returns true, the form will be saved and closed.
function PreSaveAction() {
var options = {
"url": "https://example.com/_api/web/lists/getbytitle('TestList')/items",
"method": "GET",
"headers": {
"Accept": "application/json; odata=verbose"
}
}
$.ajax(options).done(function (response) {
var actualHours = response.d.results[0].ActualHours
var personalHours = $("input[title$='Personal Hours']").val();
var regex = /^\d*\.?\d+$/ // Forces digit after decimal point
if (personalHours && regex.test(personalHours)) { // Run if input is not blank and passes RegEx
if (response.d.results[0].__metadata.etag.replace(/"/g, "") == $("td .ms-descriptiontext")[0].innerText.replace("Version: ", "").split('.')[0]) {
// Run if item's data from REST matches version shown in form
addChildItem(id, title, personalHours, actualHours)
}
}
});
return true; // firing before request above begins
}
The function is returning as true before running the jQuery AJAX call which runs addChildItem() that manipulates fields within the form and posts relevant data to a separate list.
function addChildItem(id, title, personalHours, actualHours) {
$.ajax({
method: "POST",
url: "https://example.com/_api/web/lists/getbytitle('ChildList')/items",
data: JSON.stringify({
__metadata: {
'type': 'SP.Data.ChildListListItem'
},
ParentID: id,
Title: title,
HoursWorked: personalHours
}),
contentType: "application/json;odata=verbose",
headers: {
"Accept": "application/json; odata=verbose",
},
success: function (data) {
console.log("success", data);
var actualHoursNum = Number(actualHours);
var personalHoursNum = Number(personalHours);
$("input[title$='Actual Hours']").val(actualHoursNum + personalHoursNum);
$("input[title$='Personal Hours']").val('');
// Input is getting cleared on save but shows previous number when form is opened again
},
error: function (data) {
console.log("error", data);
}
});
}
This is causing the form to accept the field value manipulations but only after the save and before the automatic closure of the form.
I need PreSaveAction() to wait until after addChildItem() is successful to return true but I'm not sure how to do this. I have tried using a global variable named returnedStatus that gets updated when addChildItem() is successful but the return value in PreSaveAction() still gets looked at before the jQuery AJAX call is ran.
How can I solve this?
I got a similar case by setting async: false to add user to group in PreSaveAction.
Original thread
<script language="javascript" type="text/javascript">
function PreSaveAction() {
var check = false;
var controlName = 'MultiUsers';
// Get the people picker object from the page.
var peoplePickerDiv = $("[id$='ClientPeoplePicker'][title='" + controlName + "']");
var peoplePickerEditor = peoplePickerDiv.find("[title='" + controlName + "']");
var peoplePicker = SPClientPeoplePicker.SPClientPeoplePickerDict[peoplePickerDiv[0].id];
if (!peoplePicker.IsEmpty()) {
if (peoplePicker.HasInputError) return false; // if any error
else if (!peoplePicker.HasResolvedUsers()) return false; // if any invalid users
else if (peoplePicker.TotalUserCount > 0) {
// Get information about all users.
var users = peoplePicker.GetAllUserInfo();
for (var i = 0; i < users.length; i++) {
console.log(users[i].Key);
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/sitegroups(22)/users";
$.ajax({
url: requestUri,
type: "POST",
async: false,
data: JSON.stringify({ '__metadata': { 'type': 'SP.User' }, 'LoginName': '' + users[i].Key + '' }),
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function(data) {
console.log('User Added');
check = true;
},
error: function (error) {
console.log(JSON.stringify(error));
check = false;
}
});
}
}
} else {
console.log('No user');
}
return check;
}
</script>

Create variable in one script and use in another script. JQuery/HTML/JS

How can I turn the results from Script 1, Name, Email, Teamsinto variables I can use in script 2?
I am making an API call to fetch some JSON I then want to use certain values as text in a message I then send to slack.
Example.
$('.Name').html(data.user.name); // Returns John
$('.Email').html(data.user.email); // Returns John#John.com
$('.Teams').html(data.user.teams[0].name); // Returns JohnsTeam
var text = 'Hello my name is $Name + my email is $Email + From $Teams'
Output = Hello my name is John my email is John#John.com From JohnsTeam
Script 1
function currentUrl() {
return new Promise(function (resolve) {
chrome.tabs.query({
active: true,
currentWindow: true
}, function(tabs) {
resolve(tabs[0].url)
})
})
}
function userIdfromUrl(url) {
var parts = url.split('/')
return parts[parts.length - 1]
}
var authorizationToken = "xxxxxxxxxxxxxxxxxxxxxxxxx";
function myapiRequest(endpoint, options) {
$.ajax($.extend({}, {
type: 'GET',
dataType: "json",
success: function(data) {
$('.Name').html(data.user.name);
$('.Email').html(data.user.email);
$('.Teams').html(data.user.teams[0].name);
},
url: "https://api.myapi.com/" + endpoint,
headers: {
"Authorization": "Token token=" + authorizationToken,
"Accept": "application/vnd.myapi+json;version=2"
}
},
options));
}
currentUrl()
.then(function (url) {
return userIdfromUrl(url)
})
.then(function (userId) {
return myapiRequest('users/' + userId + '?include%5B%5D=contact_methods&include%5B%5D=teams')
})
.then(function (data) {
console.log(data.user.name)
console.log(data.user.email)
console.log(data.user.teams[0].name)
})
Script 2
$(document).ready(function(){
$('#contact-submit').on('click',function(e){
e.preventDefault();
var url = 'https://hooks.slack.com/services/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
var text = 'This is a message'
$.ajax({
data: 'payload=' + JSON.stringify({
"text": text // What I want to dynamically change
}),
dataType: 'json',
processData: false,
type: 'POST',
url: url
});
});
});
One great solution is to set the variable you get from the response in the HTML5 localstorage as follows:
Inside ur success:
success: function(data) {
localStorage.setItem("urdata",JSON.stringify(data));
}
In the other script, u can retrieve the data like this:
var data = localStorage.getItem("urdata"); data = JSON.parse(data);

Uncaught ReferenceError: _ is not defined at causesDataService.js:56 at causesDataService.js:64

A little background. I created an ASP.MVC web app using SQL database for users and "causes" which can be added to the web app. the following faults are coming up. I will faults and code.
Uncaught ReferenceError: _ is not defined
at causesDataService.js:56
at causesDataService.js:64
Uncaught ReferenceError: _ is not defined
at _mixins.js:2
at _mixins.js:7
Uncaught SyntaxError: Unexpected token )
Ok so now below code.....:::
MIXINS
var _mixIns = (function () {
_.mixin({
numberWithCommas: function (value) {
return value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
});
}());
Cases Data Service::
var httpVerbs = {
POST:'POST',
PUT: 'PUT',
GET: 'GET',
DEL: 'DELETE'
};
var causesDataService = (function () {
var ds = {
commit: function (type, url, data) {
// Remove 'id' member to perpare for INSERT
if (type === httpVerbs.POST) {
delete data['id'];
}
return $.ajax({
type: type,
url: url,
data: data,
dataType: 'json'
});
},
del: function (data) {
return this.commit(httpVerbs.DEL, '/api/causes/' + data.id);
},
save: function (data) {
var
type = httpVerbs.POST,
url = '/api/causes';
if (data.id > 0) {
type = httpVerbs.PUT;
url += '/' + data.id;
}
return this.commit(type, url, data);
},
saveImage: function (data) {
return $.ajax({
type: httpVerbs.POST,
url: '/causes/uploadimage',
processData: false,
contentType: false,
data: data
});
},
};
_.bindAll(ds, 'del', 'save');
return {
save: ds.save,
saveLocal: ds.saveLocal,
saveImage: ds.saveImage,
}
})();

How To Test Unstructured Javascript/JQuery

I'm faced with trying to add testing to a lot of code like the following. I know I can use mockjax to to intercept the ajax calls. But I don't how to test the $.ajax({...}) calls in isolation. I'd appreciate a good refactoring approach, but I'd also like to avoid rewriting the entire app.
I've gotten a start in other areas using qunit, and I like it. But I'm open to other suggestions too. How should I proceed?
function submitSync(repFrom, continuousRep, storedPassword) {
// var repTriggered = false;
if (repFrom !== '' && (storedPassword !== null || storedPassword !== "")) {
var secureHome = "http://" + homeUser + ":" + storedPassword + "#" + window.location.host + "/" + homeURL;
var theSource = repFrom.split("/");
var singleDocumentReplication = (theSource.length === 5);
/*
* DELETE existing replications. There will normally be no more than 1.
* Do not delete replications for application updates.
* Note that we don't allow the user to create continuous replications.
*/
$.getJSON(currentHost + '/_replicator/_all_docs', function (data) {
$.each(data.rows, function (i, theRow) {
$.ajax({
url: currentHost + '/_replicator/' + theRow.id,
type: "GET",
dataType: 'json',
async: false,
contentType: "application/json",
success: function (doc) {
if (doc._id !== "_design/_replicator" && (typeof doc.source !== 'undefined' && !doc.source.match(onlineBase + '/' + remoteDB))) {
$.ajax({
url: "/_replicator/" + doc._id + "?rev=" + doc._rev,
type: "DELETE",
contentType: "application/json",
success: function () {
console.log('Replication deleted: ' + doc._id + '?rev=' + doc._rev);
}
});
}
}
});
});
});
if (singleDocumentReplication) {
var theDoc = theSource[4];
var repFromBase = repFrom.substr(0, repFrom.indexOf(theDoc) - 1);
$.ajax({
url: "/_replicator",
type: "POST",
data: JSON.stringify({ "source": repFromBase, "target": secureHome,
"userCtx": { "name": homeUser, "roles": ["_admin", homeUser] },
"continuous": continuousRep,
"retries_per_request": 10,
"http_connections": 3,
"doc_ids": [theDoc]
}),
contentType: "application/json",
error: function () {
dialog(libLang.noSync);
},
success: function (message) {
if (message) {
dialog(libLang.synced);
}
repTriggered = true;
}
});
} else {
$.ajax({
url: "/_replicator",
type: "POST",
data: JSON.stringify({ "source": repFrom, "target": secureHome,
"userCtx": { "name": homeUser, "roles": ["_admin", homeUser] },
"continuous": continuousRep,
"retries_per_request": 10,
"http_connections": 3
}),
contentType: "application/json",
error: function () {
dialog(libLang.noSync);
},
success: function (message) {
if (message) {
dialog(libLang.synced);
}
repTriggered = true;
}
});
}
}
}
Looks like you've got a ton of code duplication. My recommendation would be to put your ajax calls into modules and pass the $.ajax as a dependency.
So:
function myModule(ajaxDependency, anyOtherDependency) { }
This way in your unit test you simply check to make sure your dependecies behave a certain way. And it looks like it will eliminate all your DRY issues.

Categories

Resources