378

I need to parse the query string www.mysite.com/default.aspx?dest=aboutus.aspx. How do I get the dest variable in JavaScript?

Community
  • 1
  • 1
sinaw
  • 3,825
  • 2
  • 14
  • 5
  • function qs(search_for) { var query = window.location.search.substring(1); var parms = query.split('&'); for (var i = 0; i < parms.length; i++) { var pos = parms[i].indexOf('='); if (pos > 0 && search_for == parms[i].substring(0, pos)) { return parms[i].substring(pos + 1);; } } return ""; } //using : document.write(qs("isFolderLevel")); – Kunal Goel Jan 21 '15 at 08:10
  • http://codepen.io/iegik/pen/NGRzoY?editors=101 – iegik Sep 25 '15 at 12:31
  • Old threat but still people are searching for it like me,Here is good snippet https://gist.github.com/cowboy/1025817 – Neelesh Sep 12 '16 at 05:13
  • I've written a package you might like, **[uqs](https://github.com/download/uqs)**, that let's you just do `var params = QS.parse(location.search); console.info(params['dest']); // > 'aboutus.aspx'` – Stijn de Witt Jul 01 '17 at 23:41
  • I just use the query-string package: https://www.npmjs.com/package/query-string – Maxime R. Dec 23 '17 at 21:29
  • not a duplicate. *getting* is different than *parsing*. – worc May 22 '18 at 20:33
  • 18
    There's already a (non IE) function to do this in native javascript, no need to re-invent the wheel: https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams – PeterT Feb 11 '19 at 02:31
  • All the answers for this question are missing one crucial component as specified at https://url.spec.whatwg.org/#concept-urlencoded-parser -- replacement of the plus sign in query string variable names and values, with space. – amn May 22 '19 at 09:23
  • this is the most compact version: `const qs = (qs) => qs.substring(1).split('&').reduce((m, arg) => {const [key, value] = arg.split('='); m[key] = value; return m;}, {});`. remember the value that you need to pass to this function should be like this `?aaa=12&b&c` the result will be a map of all the keys and values. – Ali May 26 '19 at 22:14
  • Have a look at [this solution](http://www.netlobo.com/url_query_string_javascript.html). Using his function, you would just not to call `gup('dest')` to grab the URL `dest` parameter. – Gert Grenander Jun 12 '10 at 03:29
  • If you need a small, isomorphic solution check out https://bundlephobia.com/result?p=isomorphic-querystring@1.2.3 – lifeiscontent May 05 '20 at 19:09
  • Simple solution is var url = "www.mysite.com/default.aspx?dest=aboutus.aspx" var query = new URLSearchParams(url.split("?")[1]) query.get('dest') – Sandeep Nov 03 '20 at 06:55
  • The `search` property of the [`Location`](https://developer.mozilla.org/en-US/docs/Web/API/Location/search) interface provides the query string and most modern browsers provide [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/get#examples) to make life easier. – Tanner Dolby Apr 26 '21 at 06:42

11 Answers11

366

Here is a fast and easy way of parsing query strings in JavaScript:

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]);
        }
    }
    console.log('Query variable %s not found', variable);
}

Now make a request to page.html?x=Hello:

console.log(getQueryVariable('x'));
Tarik
  • 73,061
  • 78
  • 222
  • 327
  • 11
    you should also decode any special characters that have been percent-encoded – user102008 Sep 03 '10 at 18:18
  • 42
    Easy, but not very fast if you need to get more than one query value. I think a better abstraction is to return a JS object with all the name value pairs from the query string – Juan Mendes Sep 04 '12 at 23:37
  • 11
    Also, the split("=") is not good enough, you can have a "name=value" pair where value contains a non-encoded '='. The solution to that is to do an indexOf('=') to find the first '=', and the substring before and after. – Timothée Groleau Nov 20 '12 at 05:15
  • 11
    what about `?this=1&this=2&this=3` – Skylar Saveland Mar 16 '13 at 22:12
  • 1
    For CopyPasters out there ;) I'd put console && console.log otherwise there would be JS errors when console doesn't exist which would be the case on your visitor's end. – Svetoslav Marinov Nov 06 '14 at 17:32
  • @TimothéeGroleau no, the solution is to use split's limit argument: vars[i].split('=', 2) – gotofritz Jun 16 '15 at 10:45
  • 2
    @gotofritz, I don't think that does the same thing: "a=b=c".split("=", 2) gives you [ 'a', 'b' ], what you'd want instead is ['a', 'b=c'] – Timothée Groleau Jun 22 '15 at 08:19
  • 1
    @TimothéeGroleau true - I always assumed it worked like in PHP - it doesn't – gotofritz Jun 22 '15 at 10:21
  • 1
    @TimothéeGroleau and Perl ```perl -e 'print join(" -- ", split /=/, "a=b=c", 2)'``` --> ```a -- b=c``` – timkay Jun 21 '18 at 01:14
  • 1
    breaks when `?a=b=c` – Spongman Nov 12 '18 at 21:06
  • Not to mention this has no clue whatsoever on deeply nested and array values such as: `post[title]` or `post[images][]`. Still good for simple stuff though, depending on your (nesting / multi value) needs. – SidOfc Nov 13 '18 at 13:28
  • 1
    Crashes if search is something like `?x&y=3` (don't trust user input). Alternative: `const match = window.location.search.substring(1).match(new RegExp(variable + '=([^&]*)')); return match ? match[1] : null` – Znarkus May 28 '19 at 13:09
  • @DanieleTesta maybe it was long time – Svetoslav Marinov Aug 29 '19 at 15:29
  • As many have already pointed out; the solution works but does not cover all cases. The below answer is a better solution imho. – Kermit Sep 01 '19 at 11:07
  • @Znarkus Using a RegExp like that does a ton of superfluous work (including matching many times), and it fails to encode `variable` for both query string syntax (`encodeURIComponent`) and RegExp syntax (many special characters must be backslash-escaped). I would not recommend solving a problem with regular expressions that can be solved trivially with `indexOf` and `substring`. – AndrewF Apr 02 '20 at 22:31
  • also there will be an issue if you params it base64 string which can contain == at the end and token is not valid – Ivan Salo Nov 01 '20 at 15:06
182
function parseQuery(queryString) {
    var query = {};
    var pairs = (queryString[0] === '?' ? queryString.substr(1) : queryString).split('&');
    for (var i = 0; i < pairs.length; i++) {
        var pair = pairs[i].split('=');
        query[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1] || '');
    }
    return query;
}

Turns query string like hello=1&another=2 into object {hello: 1, another: 2}. From there, it's easy to extract the variable you need.

That said, it does not deal with array cases such as "hello=1&hello=2&hello=3". To work with this, you must check whether a property of the object you make exists before adding to it, and turn the value of it into an array, pushing any additional bits.

jpaugh
  • 5,719
  • 4
  • 33
  • 83
MT4000
  • 2,023
  • 1
  • 11
  • 6
  • if b is an array of one element then this function will fail. ex. http://somesite.com/?varrible1=data&varrible2= ex. http://somesite.com/?varrible1=data&varrible – jdavid.net Dec 21 '12 at 04:53
  • 1
    Here are Jasmine tests for this: https://gist.github.com/amyboyd/68a86fe3f65a77fcfc7f – Amy B Sep 22 '14 at 10:22
  • `for (var i in a)` fails as it might enumerate object names in addition to array index values. – radiospiel Jan 23 '15 at 15:01
  • sorry i had to downvote - but for (var in..) loops without using hasOwnProperty is extremely bad practice... – jebbie Mar 19 '15 at 09:27
  • 14
    Fixed bugs and updated the code. Sorry, I want to shout it out loud here: "Javascript, why we have to do this manually? Making mistakes! Isn't JS intended to work in browser and help people in web development? – Dan Aug 20 '15 at 15:13
  • Sorry but I didn't get the argument for using `hasOwnProperty` there, you're doing a `split` to an array and then looping straight over it, where do you see the danger @jebbie? – Dominic Mar 05 '16 at 16:07
  • well it's corrected now - it's not a "for in" loop anymore which takes out the danger.. in operator will loop over every value of the prototype, so if Array.prototype was extended by some libraries with some funny things, you could end up picking such unwanted stuff too.. most of the cases it's very unlikely but enough so IDE's like web-storm will complain about a missing "hasOwnProperty" check in "for in" loops – jebbie Mar 05 '16 at 23:58
  • @Dan Yeah, I love parseStr() in PHP. – wolfrevo Mar 19 '16 at 15:31
  • 1
    This works, just add an if statement to validate `pair[0]!=""`. – uruapanmexicansong Jun 26 '18 at 21:04
  • 1
    Could be a bit shortened: `queryString.replace(/^\?/, '').split('&')` Thanks for the solution :) – BotanMan May 06 '19 at 17:06
57

You can also use the excellent URI.js library by Rodney Rehm. Here's how:-

var qs = URI('www.mysite.com/default.aspx?dest=aboutus.aspx').query(true); // == { dest : 'aboutus.aspx' }
    alert(qs.dest); // == aboutus.aspx

And to parse the query string of current page:-

var $_GET = URI(document.URL).query(true); // ala PHP
    alert($_GET['dest']); // == aboutus.aspx 
Salman von Abbas
  • 21,808
  • 8
  • 64
  • 56
  • What does the argument in .query(true) part do? Is it to return the query as a key-value object instead of the query-string? – bigp May 24 '12 at 18:42
  • @bigp Yup `.query()` returns the query string in `foo=bar&hello=world` format while `.query(true)` parses the query string into an object, e.g., `{ foo : 'bar', hello : 'world' }`. – Salman von Abbas May 24 '12 at 21:51
  • 8
    Cool, but solutions requiring 3rd party libraries aren't ideal. I'm somewhat surprised this solution has received so many upvotes. No offense intended to @SalmanPK – Madbreaks Jun 24 '14 at 17:29
  • 15
    @Madbreaks But custom, re-inventing the wheel, not battle-tested and very limited functionality solutions are? Interesting ;) – Salman von Abbas Jun 25 '14 at 09:33
  • 6
    A good native solution is (almost) always better than a good solution requiring a 3rd party tool, is all I'm saying. – Madbreaks Jun 25 '14 at 18:35
  • 5
    Even so, it's always nice to know such a tool exists. In fact, I know exactly how to parse a query by hand, but I preferred to Google around for some better solution, and that's how I got here, in the first place. ;) – Haroldo_OK May 09 '15 at 23:18
26

Me too! http://jsfiddle.net/drzaus/8EE8k/

(Note: without fancy nested or duplicate checking)

deparam = (function(d,x,params,p,i,j) {
return function (qs) {
    // start bucket; can't cheat by setting it in scope declaration or it overwrites
    params = {};
    // remove preceding non-querystring, correct spaces, and split
    qs = qs.substring(qs.indexOf('?')+1).replace(x,' ').split('&');
    // march and parse
    for (i = qs.length; i > 0;) {
        p = qs[--i];
        // allow equals in value
        j = p.indexOf('=');
        // what if no val?
        if(j === -1) params[d(p)] = undefined;
        else params[d(p.substring(0,j))] = d(p.substring(j+1));
    }

    return params;
};//--  fn  deparam
})(decodeURIComponent, /\+/g);

And tests:

var tests = {};
tests["simple params"] = "ID=2&first=1&second=b";
tests["full url"] = "http://blah.com/?third=c&fourth=d&fifth=e";
tests['just ?'] = '?animal=bear&fruit=apple&building=Empire State Building&spaces=these+are+pluses';
tests['with equals'] = 'foo=bar&baz=quux&equals=with=extra=equals&grault=garply';
tests['no value'] = 'foo=bar&baz=&qux=quux';
tests['value omit'] = 'foo=bar&baz&qux=quux';

var $output = document.getElementById('output');
function output(msg) {
    msg = Array.prototype.slice.call(arguments, 0).join("\n");
    if($output) $output.innerHTML += "\n" + msg + "\n";
    else console.log(msg);
}
var results = {}; // save results, so we can confirm we're not incorrectly referencing
$.each(tests, function(msg, test) {
    var q = deparam(test);
    results[msg] = q;
    output(msg, test, JSON.stringify(q), $.param(q));
    output('-------------------');
});

output('=== confirming results non-overwrite ===');
$.each(results, function(msg, result) {
    output(msg, JSON.stringify(result));
    output('-------------------');
});

Results in:

simple params
ID=2&first=1&second=b
{"second":"b","first":"1","ID":"2"}
second=b&first=1&ID=2
-------------------
full url
http://blah.com/?third=c&fourth=d&fifth=e
{"fifth":"e","fourth":"d","third":"c"}
fifth=e&fourth=d&third=c
-------------------
just ?
?animal=bear&fruit=apple&building=Empire State Building&spaces=these+are+pluses
{"spaces":"these are pluses","building":"Empire State Building","fruit":"apple","animal":"bear"}
spaces=these%20are%20pluses&building=Empire%20State%20Building&fruit=apple&animal=bear
-------------------
with equals
foo=bar&baz=quux&equals=with=extra=equals&grault=garply
{"grault":"garply","equals":"with=extra=equals","baz":"quux","foo":"bar"}
grault=garply&equals=with%3Dextra%3Dequals&baz=quux&foo=bar
-------------------
no value
foo=bar&baz=&qux=quux
{"qux":"quux","baz":"","foo":"bar"}
qux=quux&baz=&foo=bar
-------------------
value omit
foo=bar&baz&qux=quux
{"qux":"quux","foo":"bar"}   <-- it's there, i swear!
qux=quux&baz=&foo=bar        <-- ...see, jQuery found it
-------------------
drzaus
  • 21,536
  • 14
  • 123
  • 183
  • just tryin' to keep it simple – drzaus Jan 16 '13 at 22:25
  • What if one of the variables in query string includes = (equal) sign – Umut KIRGÖZ Jan 10 '14 at 15:11
  • @WebolizeR -- considering the value containing `=` should have been encoded, shouldn't be a problem -- http://jsfiddle.net/8EE8k/15/ – drzaus Jan 13 '14 at 18:41
  • 1
    Fails if any query string value does not have an equal sign, for example: `'?val1=1&val2&val3=4'`, because the split on '=' results in `pair[1] == null`, which `decodeURIComponent(null)` returns the string `"null"` instead of value `null`. Better to use `d(pair[1] || '')`. – Triynko Oct 24 '16 at 17:48
  • @Triynko sure, good point, although technically you'd want to avoid decoding it entirely if it was empty e.g. something like `pair[1] ? d(pair[1]) : pair[1]`. trivial enough to include for that particular use case. my old answer was meant to be a simple narrowish purpose solution that doesn't involve lots of code. – drzaus Oct 24 '16 at 18:48
  • 1
    @drzaus I used your code, but i needed duplicating parameters to be parsed as array. In case somebody have same needs, - https://jsfiddle.net/sergiyok/yywhxsqz/ – iVenGO Oct 28 '16 at 10:40
  • does not work with array ?test[]=3&test[name]=3 – dazzafact Nov 24 '18 at 18:40
  • @drzaus -- `=` is allowed in a query string value, and it does appear in the wild. In general `split` should not be used to get a prefix or suffix. At best it does extra work and at worst it causes bugs. A trivial `indexOf`/`lastIndexOf` and `substring` will suffice. – AndrewF Apr 02 '20 at 22:37
  • there, 7+ years later is (almost) everyone happy? – drzaus Apr 30 '20 at 19:04
19

Here's my version based loosely on Braceyard's version above but parsing into a 'dictionary' and support for search args without '='. In use it in my JQuery $(document).ready() function. The arguments are stored as key/value pairs in argsParsed, which you might want to save somewhere...

'use strict';

function parseQuery(search) {

    var args = search.substring(1).split('&');

    var argsParsed = {};

    var i, arg, kvp, key, value;

    for (i=0; i < args.length; i++) {

        arg = args[i];

        if (-1 === arg.indexOf('=')) {

            argsParsed[decodeURIComponent(arg).trim()] = true;
        }
        else {

            kvp = arg.split('=');

            key = decodeURIComponent(kvp[0]).trim();

            value = decodeURIComponent(kvp[1]).trim();

            argsParsed[key] = value;
        }
    }

    return argsParsed;
}

parseQuery(document.location.search);
coolaj86
  • 64,368
  • 14
  • 90
  • 108
Henry Rusted
  • 379
  • 5
  • 13
  • 2
    Is there a reason for using unescape() instead of decodeURI()? – Ghigo Nov 26 '12 at 02:43
  • 1
    I would add if(args[i].length){ as the first line in the loop in order to avoid empty keys in argsParsed. – Ghigo Nov 26 '12 at 02:55
  • 1
    @ghigo Yes, checking for a zero length key would be a good idea, perhaps after trimming though. There was no reason to use unescape(), I can't remember where I copied it from ;-) – Henry Rusted Nov 28 '12 at 11:16
  • 2
    Warning: unescape is deprecated. See: https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Functions?redirectlocale=en-US&redirectslug=Core_JavaScript_1.5_Guide%2FFunctions#escape_and_unescape_functions(Obsoleted_above_JavaScript_1.5) – fjsj Mar 01 '13 at 13:48
  • 2
    Don't use this code, it's just wrong. Trimming modifies data, unescape is used instead of decodeURIComponent and it's called in the wrong place (name and value should be parsed separately, not as a part of the name=value string). It also leaks global variables and uses '==' for comparing values. – Konrad Dzwinel Jul 18 '14 at 11:49
  • Trim is probably fine here, since 'space' should be encoded as '+', which, by the way, decodeURIComponent does not decode. In addition to decodeURIComponent, you'd have to replace '+' with ' ' to get the real names and values. – Triynko Oct 24 '16 at 17:44
  • breaks when `?a=b=c` – Spongman Nov 12 '18 at 21:05
  • @Triynko It is not correct that "'space' should be encoded as '+'." That is one convention used for certain form behaviors, but %20 is also fine in a query string. This is even codified in modern HTML standards. – AndrewF Apr 02 '20 at 22:40
14

Following on from my comment to the answer @bobby posted, here is the code I would use:

    function parseQuery(str)
        {
        if(typeof str != "string" || str.length == 0) return {};
        var s = str.split("&");
        var s_length = s.length;
        var bit, query = {}, first, second;
        for(var i = 0; i < s_length; i++)
            {
            bit = s[i].split("=");
            first = decodeURIComponent(bit[0]);
            if(first.length == 0) continue;
            second = decodeURIComponent(bit[1]);
            if(typeof query[first] == "undefined") query[first] = second;
            else if(query[first] instanceof Array) query[first].push(second);
            else query[first] = [query[first], second]; 
            }
        return query;
        }

This code takes in the querystring provided (as 'str') and returns an object. The string is split on all occurances of &, resulting in an array. the array is then travsersed and each item in it is split by "=". This results in sub arrays wherein the 0th element is the parameter and the 1st element is the value (or undefined if no = sign). These are mapped to object properties, so for example the string "hello=1&another=2&something" is turned into:

{
hello: "1",
another: "2",
something: undefined
}

In addition, this code notices repeating reoccurances such as "hello=1&hello=2" and converts the result into an array, eg:

{
hello: ["1", "2"]
}

You'll also notice it deals with cases in whih the = sign is not used. It also ignores if there is an equal sign straight after an & symbol.

A bit overkill for the original question, but a reusable solution if you ever need to work with querystrings in javascript :)

jsdw
  • 4,802
  • 3
  • 22
  • 26
11

If you know that you will only have that one querystring variable you can simply do:

var dest = location.search.replace(/^.*?\=/, '');
CB01
  • 365
  • 3
  • 7
8

The following function will parse the search string with a regular expression, cache the result and return the value of the requested variable:

window.getSearch = function(variable) {
  var parsedSearch;
  parsedSearch = window.parsedSearch || (function() {
    var match, re, ret;
    re = /\??(.*?)=([^\&]*)&?/gi;
    ret = {};
    while (match = re.exec(document.location.search)) {
      ret[match[1]] = match[2];
    }
    return window.parsedSearch = ret;
  })();
  return parsedSearch[variable];
};

You can either call it once without any parameters and work with the window.parsedSearch object, or call getSearch subsequently. I haven't fully tested this, the regular expression might still need some tweaking...

amiuhle
  • 2,505
  • 17
  • 28
  • 4
    seems like a case of "I have a problem. I'll use some regex to solve it. Now I have two problems." Tell me how this is better than @Braveyard's string parsing method. – cori Oct 10 '11 at 03:53
  • 1
    Like I wrote, it will be parsed once and cached in an object. @Braveyard's code will parse the whole hash each time you call the function, and loop through all available variables until the correct one is found. – amiuhle Dec 05 '11 at 10:26
  • 1
    @cori regular expressions vs splitting strings is just a matter of taste I guess... – amiuhle Dec 05 '11 at 10:34
  • @cori It is better as it is challenging... Though it is a more frustrated programmer's approach.. – Vishal Kumar Sahu Jul 12 '17 at 16:18
6

How about this?

function getQueryVar(varName){
    // Grab and unescape the query string - appending an '&' keeps the RegExp simple
    // for the sake of this example.
    var queryStr = unescape(window.location.search) + '&';

    // Dynamic replacement RegExp
    var regex = new RegExp('.*?[&\\?]' + varName + '=(.*?)&.*');

    // Apply RegExp to the query string
    var val = queryStr.replace(regex, "$1");

    // If the string is the same, we didn't find a match - return false
    return val == queryStr ? false : val;
}

..then just call it with:

alert('Var "dest" = ' + getQueryVar('dest'));

Cheers

Serhii Nadolynskyi
  • 4,725
  • 2
  • 19
  • 20
Madbreaks
  • 17,159
  • 7
  • 50
  • 64
  • 1
    Downvoter, would appreciate an explanation... – Madbreaks Dec 20 '12 at 16:58
  • 1
    You should first split at & and then unescape. Otherwise, this code surely fails if the value contains an encoded & or =, especially if it repeats parts of the keyword – Christian Oct 13 '20 at 16:03
5

I wanted a simple function that took a URL as an input and returned a map of the query params. If I were to improve this function, I would support the standard for array data in the URL, and or nested variables.

This should work back and for with the jQuery.param( qparams ) function.

function getQueryParams(url){
    var qparams = {},
        parts = (url||'').split('?'),
        qparts, qpart,
        i=0;

    if(parts.length <= 1 ){
        return qparams;
    }else{
        qparts = parts[1].split('&');
        for(i in qparts){

            qpart = qparts[i].split('=');
            qparams[decodeURIComponent(qpart[0])] = 
                           decodeURIComponent(qpart[1] || '');
        }
    }

    return qparams;
};
jdavid.net
  • 723
  • 9
  • 16
  • `if(parts.length <= 1 ){` created bit of confusion... – Vishal Kumar Sahu Jul 12 '17 at 16:19
  • breaks when `?a=b=c` – Spongman Nov 12 '18 at 21:05
  • @Spongman In what situations is `?a=b=c` used? – Shannon Matthews Apr 21 '21 at 00:59
  • @ShannonMatthews if you want to pass the string "b=c" to the parameter "a". or _any_ value containing the '=' character. the above code assumes the value does not contain a '='. – Spongman Apr 21 '21 at 16:40
  • Thanks @Spongman. – Shannon Matthews Apr 22 '21 at 23:17
  • technically only the key value pair is allowed to use the '=' sign un-escaped. ( = %3D) https://www.w3schools.com/tags/ref_urlencode.ASP URL Reserved Characters https://tools.ietf.org/html/rfc3986#section-2.2 URL Path Parameters https://tools.ietf.org/html/rfc3986#section-3.3 so the real question is should your code work with URLs that are not in spec, that might be a requirement for your project, but usually it's not unless you have a special case. – jdavid.net Apr 23 '21 at 00:57
  • the spec doesn't involve itself in the semantics of the encoding of the key & value fields in the query. but, obviously, if you don't want your implementation to be broken, then you should encode/decode these appropriately, as do _most_ implementations. the above code is broken in general, don't use it. – Spongman Apr 24 '21 at 19:27
  • @Spongman, [the spec in 2.2](https://tools.ietf.org/html/rfc3986#section-2.2) literally calls the '=' sign a reserved character and says it's safe for delimiting the parts of the url. the other parts of the spec detail how to have 'reserved characters' in the rest of the URL by encoding them. if you have an unencoded '=' and the intent is not part of the Key/Value Pair then the URL should fail validation, and is out of spec. like i said, maybe you have a site you are working with and you need to parse a url scheme that violates spec, but that shouldn't be the default. – jdavid.net Apr 26 '21 at 15:07
2

I wanted to pick up specific links within a DOM element on a page, send those users to a redirect page on a timer and then pass them onto the original clicked URL. This is how I did it using regular javascript incorporating one of the methods above.

Page with links: Head

  function replaceLinks() {   
var content = document.getElementById('mainContent');
            var nodes = content.getElementsByTagName('a');
        for (var i = 0; i < document.getElementsByTagName('a').length; i++) {
            {
                href = nodes[i].href;
                if (href.indexOf("thisurl.com") != -1) {

                    nodes[i].href="http://www.thisurl.com/redirect.aspx" + "?url=" + nodes[i];
                    nodes[i].target="_blank";

                }
            }
    }
}

Body

<body onload="replaceLinks()">

Redirect page Head

   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]);
            }
        }
        console.log('Query variable %s not found', variable);
    }
    function delayer(){
        window.location = getQueryVariable('url')
    }

Body

<body onload="setTimeout('delayer()', 1000)">
bobby
  • 31
  • 3