sc131
sc131

Reputation: 1

document.referrer help Javascript

I was wondering if someone could help me, I have the following javascript code on my website:

<body onload="if (document.referrer == '') self.location='https://www.thisisanexampleofmysiteurl.com';">

But I was wondering if there was a way to modify it so it contained an exception to the rule. For example, if a user typed in the url directly they would be sent to https://www.thisisanexampleofmysiteurl.com but if they were referred from a URL shortener (say fakeexample.com) then the actual web page would load rather than https://www.thisisanexampleofmysiteurl.com

Hopefully this makes sense and someone can help.

Thanks,

S

Upvotes: 0

Views: 479

Answers (1)

sebasaenz
sebasaenz

Reputation: 1956

you can add to that piece of code an else if that detects through a RegExp if the referrer is a URL shortener:

var regExp = /http:\/\/(bit.ly|goo.gl)/g;
var dr = document.referrer;
if (dr == '') {

    self.location='https://www.thisisanexampleofmysiteurl.com';

} else if (dr.match(regExp)) {

    self.location='http://www.whateverURLyouWantToLoadInstead.com';

}

I think it might be a good idea to include this code in a $(document).ready(function(){...}); as it would be more clear.

Upvotes: 1

Related Questions