How to replace previous URL parameters using javascript? - javascript

I had this function to get and replace my URL parameter:
function getURLParameters(paramName) {
var sURL = window.document.URL.toString();
if (sURL.indexOf("?") > 0) {
var arrParams = sURL.split("?");
var arrURLParams = arrParams[1].split("&");
var arrParamNames = new Array(arrURLParams.length);
var arrParamValues = new Array(arrURLParams.length);
var i = 0;
for (i = 0; i < arrURLParams.length; i++) {
var sParam = arrURLParams[i].split("=");
arrParamNames[i] = sParam[0];
if (sParam[1] !== "")
arrParamValues[i] = unescape(sParam[1]);
else
arrParamValues[i] = "No Value";
}
for (i = 0; i < arrURLParams.length; i++) {
if (arrParamNames[i] === paramName) {
return arrParamValues[i];
}
}
return "No Parameters Found";
}
}
It was working okay when I had a URL like this
https://example.com/?&page=2
But now, my URL is like this:
https://example.com/?&page=2&order=my_id&direction=ASC.
My function still replaces page=2 as page=3 etc, but other values are appended to my whole URL. How can I replace all these params in my URL

You can use split by both ? and & to get all of the params then you process them by your logic after that.
const url = "https://example.com/?&page=2&order=my_id&direction=ASC"
console.log(url.split(/[\?\&]/))

Related

Function does not execute if url (get) exists

I have a link with a variable? Sid = .... being executed, but I want that if this variable exists it does not perform the function.
get the value of the variable and if it is false execute.
URL: https://example.com/?sid=2134912fhjkdhfsjdhf234829347wdjfsdf
function oldPrice() {
var url = window.location.search.replace("?", "");
var items = url.split("");
var array = {
'id': items[20]
}
var result = array.id;
if (window.location.href != "https://www.mysite.com.br/" || result == false) {
const spans = document.querySelectorAll(".old-price.sly-old-price.no-display");
for (let i = 0; i < spans.length; i++) {
const span = spans[i];
span.classList.add("forceview");
}
}
return null;
}
oldPrice();
Use URL and URLSearchParams - like this
When it does not exist, the test is null
const url = new URL("https://example.com/?nosid=xxxx")
const searchParms = new URLSearchParams(url.search); // OR location.search for the page url params
var sid = searchParms.get('sid') ? true:false;
console.log(sid)
if (window.location.href !== "https://www.mysite.com.br/" || !sid) {
console.log("executing")
}
You can use the following code :
var url = "https://example.com/?sid=2134912fhjkdhfsjdhf234829347wdjfsdf";
if(url.includes("sid")) { console.log("true") }

Rebuild a url with the query parameters

I have a url:
http://www.example.com/gclid/YH67/utm/2908321/id/test
I would like to have the url with query parameters:
http://www.example.com/?gclid=YH67&utm=2908321&id=test
What I know is the main url http://www.example.com/
I would like to make the url to have the right parameter (I don't know the specific parameters of key/value).
Here is a simple example that I saw it works
if (window.location.href === "http://www.example.com") {
url = "http://www.example.com?gclid=test";
window.history.pushState("", "", url);
}
try this one -
function makeURL(url)
{
var mainUrl = "http://www.example.com/";
var urlArr = url.split(mainUrl);
if(urlArr[1] && urlArr[1] !== "")
{
// assuming url will always be a perfect url
var queryPoints = urlArr[1].split("/");
var queryStr = "?";
for(var i = 0; i < queryPoints.length; i+=2)
{
var key = queryPoints[i];
var value = queryPoints[i+1];
if(i+2 == queryPoints.length)
queryStr += key+ "=" + value;
else
queryStr += key+ "=" + value + "&";
}
var queriedUrl = mainUrl + queryStr;
console.log(queriedUrl);
return queriedUrl;
}
return url;
}
Invoke above function like this - makeURL("http://www.example.com/gclid/YH67/utm/2908321/id/test"). It will return you the data in query string format.
Here is an update that transform a given url to a url with query string:
var url='http://www.example.com/gclid/YH67/utm/2908321/id/test';
var domain='http://www.example.com/';
function extractParams(url,domain) {
var params=url.replace(domain,'').split('/');
var newparams={};
for (var i=0;i<params.length;i=i+2) {
newparams[params[i]]=params[i+1];
}
return newparams;
}
function httpBuildQuery(params) {
var query=[];
for (var key in params) {
query.push(key+'='+params[key]);
}
return query.join('&');
}
console.log(httpBuildQuery(extractParams(url,domain)));

Get anchor tag values in jQuery

I have a html tag like this.
<a class="employee_details" target="_blank" href="index1.php?name=user1&id=123">User</a>
I need to get the two parameter values in jquery
<script type="text/javascript">
$(function () {
$('.employee_details').click(function () {
var status_id = $(this).attr('href').split('name');
alert(status_id[0]);
});
});
</script>
Any help in getting both the parameter values in two variables in javascript.
I want to get user1 and 123 in two variables using jQuery
Thanks
Kimz
You can use URLSearchParams as a most up-to-date and modern solution:
let href = $(this).attr('href');
let pars = new URLSearchParams(href.split("?")[1]);
console.log(pars.get('name'));
Supported in all modern browsers and no jQuery needed!
Original answer:
Try this logic:
var href = $(this).attr('href');
var result = {};
var pars = href.split("?")[1].split("&");
for (var i = 0; i < pars.length; i++)
{
var tmp = pars[i].split("=");
result[tmp[0]] = tmp[1];
}
console.log(result);
So you'll get the parameters as properties on result object, like:
var name = result.name;
var id = result.id;
Fiddle.
An implemented version:
var getParams = function(href)
{
var result = {};
var pars = href.split("?")[1].split("&");
for (var i = 0; i < pars.length; i++)
{
var tmp = pars[i].split("=");
result[tmp[0]] = tmp[1];
}
return result;
};
$('.employee_details').on('click', function (e) {
var params = getParams($(this).attr("href"));
console.log(params);
e.preventDefault();
return false;
});
Fiddle.
$(function() {
$('.employee_details').on("click",function(e) {
e.preventDefault(); // prevents default action
var status_id = $(this).attr('href');
var reg = /name=(\w+).id=(\w+)/g;
console.log(reg.exec(status_id)); // returns ["name=user1&id=123", "user1", "123"]
});
});
// [0] returns `name=user1&id=123`
// [1] returns `user1`
// [2] returns `123`
JSFiddle
NOTE: Better to use ON method instead of click
Not the most cross browser solution, but probably one of the shortest:
$('.employee_details').click(function() {
var params = this.href.split('?').pop().split(/\?|&/).reduce(function(prev, curr) {
var p = curr.split('=');
prev[p[0]] = p[1];
return prev;
}, {});
console.log(params);
});
Output:
Object {name: "user1", id: "123"}
If you need IE7-8 support this solution will not work, as there is not Array.reduce.
$(function () {
$('.employee_details').click(function () {
var query = $(this).attr('href').split('?')[1];
var vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
var varName = decodeURIComponent(pair[0]);
var varValue = decodeURIComponent(pair[1]);
if (varName == "name") {
alert("name = " + varValue);
} else if (varName == "id") {
alert("id = " + varValue);
}
}
});
});
It's not very elegant, but here it is!
var results = new Array();
var ref_array = $(".employee_details").attr("href").split('?');
if(ref_array && ref_array.length > 1) {
var query_array = ref_array[1].split('&');
if(query_array && query_array.length > 0) {
for(var i = 0;i < query_array.length; i++) {
results.push(query_array[i].split('=')[1]);
}
}
}
In results has the values. This should work for other kinds of url querys.
It's so simple
// function to parse url string
function getParam(url) {
var vars = [],hash;
var hashes = url.slice(url.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
// your code
$(function () {
$('.employee_details').click(function (e) {
e.preventDefault();
var qs = getParam($(this).attr('href'));
alert(qs["name"]);// user1
var status_id = $(this).attr('href').split('name');
});
});

Does this iframe buster script look safe?

We're being asked to host a number of iframe buster scripts on our site - they allow ads which are served from external domains into iframes to expand outside of them into the host page. Our hosting provider's warned us to watch out for security holes in these scripts. Specifically, they say some of them create cross-site scripting holes by allowing a piece of Javascript to be loaded into our site from any URL.
To implement the script, you host an HTML page on your site. I'm looking at an example from the ad provider Atlas. In this case the URL is like http://domain.com/atlas/atlas_rm.htm. That page contains a script tag with src at an external URL, and here's the JS it includes:
var ARMIfbLib = function () {
function documentWrite(htmlString) {
document.write(htmlString);
}
function writeIframeBustingScript() {
var imgSrvPath = getTlDirectoryFromQueryString(getParameterString());
if (imgSrvPath != "") {
var scriptURL = imgSrvPath + getScriptFileName();
ARMIfbLib.DocumentWrite("<script language='javascript' type='text/javascript' src='" + scriptURL + "'></scr" + "ipt>");
}
}
return {
WriteIframeBustingScript: writeIframeBustingScript,
DocumentWrite: documentWrite
}
}();
function getValueFromDelimitedString(paramKey, delimiter, queryString) {
if (paramKey == "imgSrv")
return getValueFromProperties();
var re = new RegExp(paramKey + "=" + "(.*?)" + "(" + delimiter + "|$)");
var matchArray = queryString.match(re);
if (matchArray == null)
return "";
else
return matchArray[1];
}
function getValueFromProperties() {
var iframename = unescape(self.name);
if (iframename.indexOf("<form") >= 0) {
var params = iframename.split("<input ");
for (var i = 1; i < params.length; i++) {
var parts = params[i].split(" ");
for (var j = 0; j < parts.length; j++) {
var param = parts[j].split("=");
if (param[0].indexOf("name") >= 0 && param[1].indexOf("TL_files_path") >= 0) {
param = parts[j + 1].split("=");
if (param[0].indexOf("value") >= 0) {
var value = param[1].substr(1, param[1].indexOf(">"));
value = value.substr(value, value.lastIndexOf("/"));
value = value.substr(value, value.lastIndexOf("/") + 1);
return unescape(value);
}
}
}
}
}
else if (iframename.indexOf("adparamdelim") >= 0) {
var params = iframename.split("adparamdelim");
for (var i = 0; i < params.length; i++) {
var param = params[i].split("=");
if (param[0].indexOf("TL_files_path") >= 0) {
var value = param[1];
value = value.substr(value, value.lastIndexOf("/"));
value = value.substr(value, value.lastIndexOf("/") + 1);
return value;
}
}
}
else if (/^\{.*\}$/.test(iframename)) {
try {
eval('var results = ' + iframename);
var value = results.TL_files_path;
value = value.substr(value, value.lastIndexOf("/"));
value = value.substr(value, value.lastIndexOf("/") + 1);
return value;
} catch (e) {
return "";
}
} else {
var params = iframename.split("&");
for (var i = 0; i < params.length; i++) {
var param = params[i].split("=");
if (param[0].indexOf("TL_files_path") >= 0) {
var value = unescape(param[1]);
value = value.substr(value, value.lastIndexOf("/"));
value = value.substr(value, value.lastIndexOf("/") + 1);
return value;
}
}
}
return "";
}
function getTlDirectoryFromQueryString(sLocation) {
var queryVar = getValueFromDelimitedString("imgSrv", "a4edelim", sLocation);
var temp = queryVar.substr(0, queryVar.lastIndexOf("/"));
var tlDir = temp.substr(0, temp.lastIndexOf("/") + 1);
return tlDir;
}
function getDocumentQueryString() {
return window.location.search;
}
function getIframeParameterString() {
var ret = "";
var qs = getDocumentQueryString();
if (qs.length > 0)
ret = qs.substring(1);
return ret;
}
function getScriptParameterString() {
var ret = "";
var scripts = document.getElementsByTagName('script');
for (var i = 0; i < scripts.length; i++) {
var scriptSrc = scripts[i].src;
if (scriptSrc.toLowerCase().indexOf("newiframescript") != -1 && scriptSrc.indexOf("?") != -1) {
ret = scriptSrc.substr(scriptSrc.indexOf("?") + 1);
break;
}
}
return ret;
}
function getParameterString() {
var qs = getIframeParameterString();
if (qs.length > 0 && qs.indexOf("a4edelim") > 0)
return qs;
return getScriptParameterString();
}
function getScriptFileName() {
var armdelim = ",";
var fileName = "ifb.0";
var queryString = getParameterString();
var parmValue = "";
if (queryString.length > 0) {
parmValue = getValueFromDelimitedString("armver", "a4edelim", queryString);
}
if (parmValue.length > 0) {
var fileNames = parmValue.split(armdelim);
for (var i = 0; i < fileNames.length; i++) {
if (fileNames[i].toLowerCase().indexOf("ifb") != -1) {
fileName = fileNames[i];
break;
}
}
}
return fileName + ".js";
}
if (typeof(armTestMode) == "undefined") {
ARMIfbLib.WriteIframeBustingScript();
}
I've spent a couple of hours studying this to try and work out what it's doing, but I've got bogged down in the different function calls. It seems to be grabbing a query string parameter or else a value from the name of an iframe, presumably the iframe the contains the ad.
Can anyone understand what this JS is doing? Does it look fairly safe from a XSS point of view?
=========================================
EDIT
In case useful to anybody else, we mentioned this concern to the providers, and their response was:
The iframe buster page will only work if it is in an iframe
The code in the ftlocal.html file will only work if the domain of the iframe is already the same as the domain of the parent page – So any code would already have access to the parent page anyway
The the JS script creates a dynamically generated script tag in your page.
ARMIfbLib.DocumentWrite("<script language='javascript' type='text/javascript' src='" + scriptURL + "'></scr" + "ipt>");
If you dig into where scriptURL comes from, it appears to be a parameter passed to window.location.search (the query string).
From what I can see this effectively allows any script to be passed to your page on the query string rendering it vulnerable to DOM XSS, unless it is effectively secured to allow the domain to be set by the frame name in your page. I'd do some testing using your own domains and passing the query string variables that are searched for (the string literals in the JS).

Extract value from certain query from string in jQuery

var test = "http://www.example.org/search?q=whatever&another=moretext";
How can I extract another's value (moretext) in the query string above and make a variable out of it?
var test = "http://www.example.org/search?q=whatever&another=moretext";
var another = test.split('another=');
another is an array with another[0] = 'http://www.example.org/search?q=whatever&' and another[1] = 'moretext'.
keep this function in your bag :
function querySt(qsName, url)
{
var theUrl;
if (url == null || url == undefined)
theUrl = window.location.search.substring(1); else theUrl = url;
var g = theUrl.split("&");
for (var i = 0; i < g.length; i++) {
var pair = g[i].split("=");
if (pair[0].toLowerCase() == qsName.toLowerCase())
{
return pair[1];
}
}
return null;
}
Usages
alert(querySt("another")+' '+querySt("q"));

Categories