Skip to content

Instantly share code, notes, and snippets.

@bwedding
Created February 27, 2018 04:09
Show Gist options
  • Save bwedding/60082242b9d59921d3dbb3efa1223aa6 to your computer and use it in GitHub Desktop.
Save bwedding/60082242b9d59921d3dbb3efa1223aa6 to your computer and use it in GitHub Desktop.
JS To read a GET query string and redirect if it matches some value. Used for coupon codes.
<script>
// Function to get the GET parameters
const getGET = () =>
{
// Read the URI the user arrived with
const loc = document.location.href;
// Find out if it has a question mark
if(loc.indexOf('?')>0)
{
// If does, so get the first chunk of text after the question mark
const getString = loc.split('?')[1];
// Now, get all the way to the ampersand into a string called GET
const GET = getString.split('&');
const get = {};
// Loop through that string and break it into separate pieces by the equals sign
for(let i = 0, l = GET.length; i < l; i++)
{
const tmp = GET[i].split('=');
get[tmp[0]] = unescape(decodeURI(tmp[1]));
}
// Return this as a set of keys and values e.g. coupon, 12345
return get;
}
}
// Listen for the page to load. When it does, run this code
document.addEventListener('DOMContentLoaded', () =>
{
// Call our get function above and get the query strings in an array of key values
const values = getGET();
// If we got something, announce it
if(values)
{
// For all the keys we found, pop an alert with the key and value
for(const index in values)
{
if( index == 'couponcode' && values[index] == '10BUCKSOFF')
{
alert("You get $10 off");
window.location = "https://branpaul.convertri.com/10bucksoff";
}
}
}
// If we didn't find a query string, announce that
else
{
alert("You're Here Naked!");
// Do nothing
}
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment