1

I'm currently using the following code to add "?skin=skin_name" to a url whenever someone lands on a particular page. This allows us to load different themes that we're testing against one another.

So if someone lands on www.example.com this script (running in optimizely) will redirect the visitor to www.example.com?skin=skin_name.

The script also keeps the ?skin=skin_name from being appended if the ?skin=skin_name is already present in the url.

if(window.location.href.indexOf('?skin=skin_name') > -1){

} else {
   /* _optimizely_redirect=http://custom */
var url = window.location,redirect_url = 'http://' + url.hostname + url.pathname + '?skin=skin_name' +url.search; 
window.location = redirect_url;

}

The problem I am having is when there are already campaign parameters attached to the url, they are being overwritten by the script.

So, if the existing url is www.example.com?utm_source=test&utm_medium=test&utm_campaign=test

the above script is causing the page to load as www.example.com?skin=skin_name?utm_source=test&utm_medium=test&utm_campaign=test which is causing the visitor to be tracked incorrectly in analytics.

What I'm looking for is a script that will produce the following url:

www.example.com?utm_source=test&utm_medium=test&utm_campaign=test**&skin=skin_name**

when there is already "?utm_source=test&utm_medium=test&utm_campaign=test" present, but will produce

www.example.com?skin=skin_name when there is already not a "?" present in the url (so in one case, skin=skin_name is appended using a "&" and in the other case, it is appended using "?" depending on whether a "?" was present in the first place).

Any help is greatly appreciated.

Tom Enns
  • 172
  • 3
  • 15

3 Answers3

1

You can check the location.search property for a value

var query = window.location.search;

if( query.indexOf('skin=skin_name') === -1 ) {
    var sign = query.trim().length === 0 ? '?' : ':';

    window.location.search = sign + 'skin=skin_name';
}  else {
   /* _optimizely_redirect=http://custom */
}
adeneo
  • 312,895
  • 29
  • 395
  • 388
0

It should be simpler if you try to use location.serach property which will be empty if there are no query string in the URL:

if (location.search) {
    // there is GET parameters already in href, use &
} else {
    // no parameters, use ?
}

Based on the value of the query string you decide what to use: either ? (no GET parameters yet), or & there are already some parameters present.

dfsq
  • 191,768
  • 25
  • 236
  • 258
0
if (location.href.indexOf("?") !== -1) {
    // There is/are querystring(s).
    // Hence, append yours, such as &key=val
} else {
    // No querystrings
    // Add yours, such as ?key=val
}
lshettyl
  • 8,166
  • 4
  • 25
  • 31