Domain Based Javascript Referrer Validation

I need JS on the page to check if the referrer is the previous page from the same domain.

The URL of the JS page is formatted as follows:

http://subdomain.site.com/dir/page?vs=123456

There may be several previous pages. Therefore, JS needs to verify domain matching.

If the domain is different, I want to send the user to another page.

Here is what I tried to work:

var matchHost = /^https?:\/\/.*\//; var match = matchHost.exec(document.referrer); var domain = "http://subdomain.site.com/dir/"; if (match !== domain) { window.location.href = domain; } 

But not quite working.

Any ideas?

+4
source share
2 answers

You may not need a regular expression. You know the length of your domain, for example, with the url http://example.com , count the characters, and then split the string according to the domain length of the referral URL, then cmopare this with your domain url! It's all.

+1
source

In your case, match is an array of matching strings. Therefore, he will never be equal. You need to compare match[0] :

 if (match.length== 0 || match[0]!== domain) ... 

Or you can avoid the regex by doing the following:

 if (document.referrer.substr (0, domain.length).toLowerCase()!== domain) ... 
+1
source

Source: https://habr.com/ru/post/1447842/


All Articles