Get pathname along with PHP vars using JavaScript? - javascript

I want to save an entire URL paths to a variable, including the php vars, eg:
mysite.com/pagename?id=2
I can use
var pathname = window.location.pathname;
but this only retrieves the URL without the variables.
Is there a function to retrieve the URL as a literal string?

This should work
window.location.href

Have you tried see if it works:
document.URL

Can you try this,
// Get current page url using JavaScript
var currentPageUrl = "";
if (typeof this.href === "undefined") {
currentPageUrl = document.location.toString().toLowerCase();
}
else {
currentPageUrl = this.href.toString().toLowerCase();
}
Ref: http://www.codeproject.com/Tips/498368/Get-current-page-URL-using-JavaScript

It's hard , this answer explains how to implement it from the top response:
function getQueryParams(qs) {
qs = qs.split("+").join(" ");
var params = {}, tokens,
re = /[?&]?([^=]+)=([^&]*)/g;
while (tokens = re.exec(qs)) {
params[decodeURIComponent(tokens[1])]
= decodeURIComponent(tokens[2]);
}
return params;
}
//var query = getQueryParams(document.location.search);
//alert(query.foo);

Related

How to generate hash512 in pre-request from request that has {{variables}} in uri

So I m working on API when i need to set x-auth header for every request in PRE-REQUEST script.
I have variables in my request url i.e {{baseUrl}}{{basePath}}{{businessID}}/users?name={{userName}}......etc
I need to take whole address and add secretKey variable to the end of address, then get hash512 from it.
I was able to achieve that if i have no variables in my address i.e.: dummy.com/12321-e213-21-3e?name=John
I did this by :
var secret = "1234qwerHr2";
var url = request.url.slice(9); //sliced because I don't need to include baseUrl to hash
var hashedPayload = CryptoJS.enc.Hex.stringify(CryptoJS.SHA512(url+secret));
This will return the desired result.
Here is what I logged when trying the same code with variables
console.log(url); =>>>>>>> asePath}}{{businessID}}/users?name={{userName}}......etc
All variables defined , that`s for sure
Basically question is : how to get url with values of variables using var url = request.url; I need not {{businessID}}/users?name={{userName}} but 12321-e213-21-3e?name=John
I lost source where i found it. Somewhere on postman github issue thread
var secret = pm.globals.get("devSecretKey");
pm.myUtility = {
interpolateVariable: function (str) {
return str.replace(/\{\{([^}]+)\}\}/g, function (match, $1) {
// console.log(match)
let result = match; //default to return the exactly the same matchd variable string
if ($1) {
let realone = pm.variables.get($1);
if (realone) {
result = realone
}
}
return result;
});
},
getUrl: function () {
let url = pm.request.url.getRaw();
url = this.interpolateVariable(url)
let {
Url
} = require('postman-collection')
return new Url(url);
},
getUrlTest: function () {
let url = pm.request.url.getRaw();
url = this.interpolateVariable(url)
// let {
// Url
// } = require('postman-collection')
//return new Url(url);
return pm.request.url.parse(url);
}
}
var requestPath = pm.myUtility.getUrl().getPath();
var requestQuery =pm.myUtility.getUrl().getQueryString();
var hashedPayload = CryptoJS.enc.Hex.stringify(CryptoJS.SHA512(requestPath+"?"+requestQuery+secret)); //I added '?' because when you use getQueryString() i does not have '?' before query
pm.environment.set("tempAuthHash", hashedPayload);// use this in your header
This function he wrote is converting your {{variable}} to 'variableValue'
No need to change anything in his functions if you are not good with coding. Guy who created it has golden hands. Just place in your pre request

Get subsection of redirect uri in query string

So I have a URL that looks like this:
localhost:9031?redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Fcallback&scope=test
I want to redirect to the URL localhost:8080/something which makes use of part of the redirect uri but drops the /callback from it.
In order to get the redirect uri I have a method that does the following and I pass it the string redirect_uri:
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
if (decodeURIComponent(pair[0]) == variable) {
return decodeURIComponent(pair[1]);
}
}
}
This gives me back the string http://localhost:8080/callback. Then to get the index of callback I use the following function.
function getPosition(string, subString, index) {
return string.split(subString, index).join(subString).length;
}
Then when the button is clicked I put it all together and do:
$('.button').click(function(e) {
var query = window.location.search.slice(1);
var redirect = getQueryVariable('redirect_uri');
var index = getPosition(redirect, '/', 3);
var baseUrl = redirect.slice(0, index);
window.location.href = baseUrl + '/something';
});
This all works as intended but it doesn't seem particularly foolproof or efficient. Looking for optimizations or suggestions to use functionality of JavaScript or JQuery that I don't know of. Looking to avoid 3rd party libraries but if they are good enough I will definitely still use them.
I would recommend letting the browser do the heavy lifting of parsing the URL. Assuming you have the decoded redirect URI from the query string, you can do the following:
var myUrl = 'http://localhost:8080/callback&scope=test';
function parseURL(url) {
var a = document.createElement("a");
a.href = url;
return {
protocol: a.protocol,
hostname: a.hostname,
port: a.port,
pathname: a.pathname
};
}
var parsedURL = parseURL(myUrl);
console.log(parsedURL.protocol + '//' + parsedURL.hostname + ':' + parsedURL.port + '/something');
You can build the base url from the results and, optionally, parse the pathname if necessary.
This is based on a well known Gist to parse URLs in JavaScript, which was introduced by John Long.
function parseURL(url) {
var parser = document.createElement('a'),
searchObject = {},
queries, split, i;
// Let the browser do the work
parser.href = url;
// Convert query string to object
queries = parser.search.replace(/^\?/, '').split('&');
for( i = 0; i < queries.length; i++ ) {
split = queries[i].split('=');
searchObject[split[0]] = decodeURIComponent(split[1]);
}
// return all fragments
return {
protocol: parser.protocol,
host: parser.host,
hostname: parser.hostname,
port: parser.port,
pathname: parser.pathname,
search: parser.search,
params: searchObject,
hash: parser.hash
};
}
// using the method
(function() {
// your first url
var temp = parseURL('localhost:9031?redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Fcallback&scope=test');
// second (the redirect_uri param);
var url = parseURL(temp.params.redirect_uri);
// now you could do:
window.location.href = url.protocol + '://' + url.host + '/whateverYoWant';
})();

How to match specific URL in JavaScript or jQuery?

I would like to match the specific URL like "http://www.google.com" in JavaScript
var str = "http://wwww.google.com"
var test = match(str)
if(test) {
alerT(match with the url)
}
Please suggest me how to do it.
If you want to test if the variable matches the specific url, you can use a simple expression.
var str = "http://wwww.google.com";
if(str == "http://wwww.google.com"){
alert('string matches');
}
It can be http or https, so better to verify the URL in two steps:
var str = "http://www.google.com";
var protocol = str.match(/http/gi);
if (protocol != null){
var url = str.match(/wwww.google.com/gi);
if(url != null){
//Do your work
}
}

Send multiple parameter in ajax request using javascript

So I want to use ajax request and I know how to use it.
But problem that i had that I want to pass parameters to request. So My first page had 4 parameter then I build url like this,
var url = "./ControllerServlet?PAGE_ID=BPCLA&ACTION=closeAssessment&SAVE_FLAG=true&closeReason="+closeReasonStr+"&closeCmt="+closeCmt;
but now parameter is increasing like now I have 20 more. So now building url like this going to be messy approach. Is there a better way to do this.
Here is my function where i am building URL in javascript function.
function closeAssessment() {
var closeReason = document.getElementById("SectionClousureReason");
var closeReasonStr = closeReason.options[closeReason.selectedIndex].value;
var closeCmt=document.getElementById("SectionCloseAssessmentCmt").value;
var url = "./ControllerServlet?PAGE_ID=BPCLA&ACTION=closeAssessment&SAVE_FLAG=true&closeReason="+closeReasonStr+"&closeCmt="+closeCmt;
ajaxRequest(url);
return;
}
edit:
As you ask here is my ajaxRequest function,
function ajaxRequest(url) {
strURL = url;
var xmlHttpRequest = false;
var self = this;
// Mozilla, Safari
if (window.XMLHttpRequest) {
self.xmlHttpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
self.xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
self.xmlHttpRequest.open("POST", strURL, true);
self.xmlHttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
self.xmlHttpRequest.onreadystatechange = function() {
if (self.xmlHttpRequest.readyState == 4) {
if (self.xmlHttpRequest.status == 200) {
var htmlString = self.xmlHttpRequest.responseText;
var parser = new DOMParser();
var responseDoc = parser.parseFromString(htmlString, "text/html");
window.close();
} else {
ajaxFailedCount++;
// Try for 1 min (temp fix for racing condition)
if (ajaxFailedCount < 1200) {window.setTimeout(function() {ajaxRequest(url)}, 50);}
else {alert("Refresh failed!")};
}
}
}
self.xmlHttpRequest.send(null);
}
You could make an object with the key/value pairs being what you want added to the URL.
var closeReason = document.getElementById("SectionClousureReason");
var params = {
PAGE_ID: 'BPCLA',
ACTION: 'closeAssessment',
SAVE_FLAG: 'true',
closeReasonStr: closeReason.options[closeReason.selectedIndex].value,
closeCmt: document.getElementById("SectionCloseAssessmentCmt").value
};
Then add them to the URL via a loop.
var url = "./ControllerServlet?";
var urlParams = Object.keys(params).map(function(key){
return encodeURIComponent(key) + '=' + encodeURIComponent(params[key]);
}).join('&');
url += urlParams;
ajaxRequest(url);
Note: I added encodeURIComponent just to be safe.
EDIT: From your comment, it seems you want to submit a <form> but you want to use AJAX to do so. In that case, you can loop over the form elements and build the above params object.
var params = {
PAGE_ID: 'BPCLA',
ACTION: 'closeAssessment',
SAVE_FLAG: 'true'
};
var form = document.getElementById('yourForm'),
elem = form.elements;
for(var i = 0, len = elem.length; i < len; i++){
var x = elem[i];
params[x.name] = x.value;
}
Build up an object of your parameters and put them in the uri through a loop like this:
var values= {
page_id: 'BPCLA',
action: 'test'
},
uri_params = [],
uri = 'http://yoururl.com/file.php?';
for (var param in values) uri_params.push( encodeURIComponent( param ) + '=' + encodeURIComponent( values[ param ] ) );
uri = uri + uri_params.join( '&' );
console.log( uri );
Or consider using POST to transport your parameters, as many browsers have limitations on the query string.
Edit: you can also build yourself a function which traverses your form and builds up the values object for you so you don't have to do it manually.
Be aware however that anyone can inject custom url paramters simpy by appending form elements before submitting the form (by using the developer tools for example) so keep that in mind.
If you are using jQuery you can use .serializeArray() or have a look at this answer for a possible function you could use.

How do you get the current sessid from web address and use it in javascript?

Sorry if this is a noob question, network admin unknowingly turned into web developer :) I am trying to understand how to get the current sessid and put it into the javascript where sessid= (current sessid), its on the web address and is generated when you visit the search page. ex: http://www.southerntiredirect.com/shop/catalog/search?sessid=uUQgRHQyekRGJcyWwTFwf5hxep7cdYlV4CdKfunmjxNOQPEgDZdJD2tNgRsD7Prm&shop_param=
<script language="JavaScript">
var url= "http://www.southerntiredirect.com/online/system/ajax_search_manufacturer?sessid=????????";
</script><script type="text/javascript" src="http://www.southerntiredirect.com/online/templatemedia/all_lang/manufacturer.js"></script><input type="hidden" name="sessid" value="sessid??????">
Use my handy-dandy library URLTools!
Library
//URLTools- a tiny js library for accessing parts of the url
function urlAnalyze(url) {
if (url == undefined) {var url = document.location.toString();}
url = url.replace(/\%20/g," ");
//seperates the parts of the url
var parts = url.split("?");
//splits into sperate key=values
if (parts[1] == undefined) {return 1;}
var keyValues = parts[1].split("&");
var key = function () {}
keyValues.forEach(function (keyValue) {
var keyAndValue = keyValue.split("=");
key[keyAndValue[0]] = keyAndValue[1];
});
return key;
}
Then, just call URLAnalyze and get the sessid key.
Usage
var urlKeys = urlAnalyze(),
sessid = urlKeys["sessid"];
here is a great function that grabs whatever you want and returns the key, value for it.
The main portion of this function gets the url using window.location.href and then performs a regular expression on it to find botht he key and the value.
I DO NOT TAKE CREDIT FOR THIS CODE.
Please go the link to see the full example
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(
/[?&]+([^=&]+)=([^&]*)/gi,
function(m,key,value) {
vars[key] = value;
});
return vars;
}
You could use a simple regexp:
var url = "http://www.southerntiredirect.com/shop/catalog/search?sessid=uUQgRHQyekRGJcyWwTFwf5hxep7cdYlV4CdKfunmjxNOQPEgDZdJD2tNgRsD7Prm&shop_param=";
var match = url.match(/sessid=([^&]+)/);
if (match === null) {
throw new Error("now what? D:");
}
var sessid = match[1];
The regexp in English: look for "sessid=" then capture anything that isn't an &

Categories

Resources