Document.referrer.indexOf

I am trying to write code that references the referrer.IndexOf value. The below code looks to see if “js.html” is in the referrer value and then shows an alert and redirects the user to another webpage. I would like the code below to do the opposite, if the referrer has js.html in the URL do nothing, if it DOES NOT show alert and redirect user. I can’t seem to figure this out and I know it should be easy. Any suggestions?


<script type="text/javascript" charset="utf-8">
if (document.referrer.indexOf('js.html') != -1) {
 alert("Access Violation");
top.location="http://www.yahoo.com";
}
</script>

THANKS!!

This Works…

<script type=“text/javascript” charset=“utf-8”>
if (document.referrer.indexOf(‘js.html’) == -1) {
alert(“Access Violation”);
top.location=“http://www.yahoo.com”;
}
</script>

This is because indexOf() returns the index at which a string is found. -1 indicates that the string was not found.

So to find out for the presence of one string within another, and you don’t care about the position, you can compare to -1 to find out.

e.g.


var someStr = "hello";

someStr.indexOf("hello"); // 0
someStr.indexOf("lo"); // 3
someStr.indexOf("sup"); // -1

// you could wrap some syntactic sugar around this:
function contains(haystack, needle, caseSensitive) {
    haystack = caseSensitive ? haystack : haystack.toUpperCase();
    needle = caseSensitive ? needle : needle.toUpperCase();
    return haystack.indexOf(needle) !== -1;
}

//now you can call
contains(document.referrer, "js.html");
//and expect a true or false result

//We can go even further by adding this:

//check if Strings already have a contain method
if ( typeof String.prototype.contains !== "function" ) {

    // Yay, we get to add it
    String.prototype.contains = function(needle, caseSensitive) {

        // just call out contains function and pass the current string
        // along as the haystack
        return contains.call(this, this, needle, caseSensitive);
    };
}

//now we can call .contains() directly on strings.
var someString = "Hello World";
someString.contains("World"); // true
someString.contains("Foo"); // false

// including document.referrer
document.referrer.contains("js.html");

Don’t forget that with privacy turned on in the browser or with certain firewall settings that the referrer field is blanked out.

Also don’t forget that as a simple header it can easily be updated to any value at all using the appropriate browser extension.

Also don’t forget that the JavaScript alert statement is for debugging purposes only and should not appear in a live web page. Here’s what alerts look like in one browser:

Here’s what they look like in another browser:

You almost certainly don’t want your visitors seeing the checkboxes in the alerts.