Using JavaScript to restrict access of JS libraries to designated domains

First stop- using JavaScript to safe guard JavaScript! You may already know that the language is capable of determining the current URL in the location field of the browser, through the property

document.location.href //returns the URL in the location field of browser (string)

With that in mind, all we need is a piece of code that compares this URL with a list of permitted ones, and if non of the later matches the former, we know the library is being accessed from an outside source (and take appropriate action). Suffice it to say such a code will need to be added directly inside the library in question in order to take effect.

Lets turn theory into reality. The below code will prevent unauthorized domains from referencing the containing JavaScript library:

//Beginning of "test.js" file
var accepted_domains=new Array("","")

var domaincheck=document.location.href //retrieve the current URL of user browser
var accepted_ok=false //set acess to false by default

if (domaincheck.indexOf("http")!=-1){ //if this is a http request
	for (r=0;r<accepted_domains.length;r++){
		if (domaincheck.indexOf(accepted_domains[r])!=-1){ //if a match is found
			accepted_ok=true //set access to true, and break out of loop

if (!accepted_ok){
	alert("You\'re not allowed to directly link to this .js file on our server!")

/////rest of your libray

We first define an array to hold a list of the "permitted" domains. Then, we enlist the JavaScript property document.location.href to get the current URL of the user's browser. Now we have both of our key witnesses in our custody- the list of permitted domains, plus the current URL (which includes domain) of the page. All that's left to do is to compare the two, and only allow the library to proceed "loading" if there is a match (if one of accepted_domain's values is contained within domaincheck). This is done using a for loop.

Notice how the code above checks to see if the document's URL contains "http" first before proceeding with the match making. The purpose of this is so that offline accessing of the JavaScript library is left out of the scrutinization process- obviously there's no point in restricting access of a library when it's accessed offline, especially if you want to be able to test the library out on your hard drive!

As mentioned, the code above should be placed at the very top of the JavaScript library you wish to restrict access to.

Using JavaScript to limit access to a library is perfectly viable, but it does have its shortcomings. Obviously you'll need to make physical changes to your library. Then there's the repetitious work involved if you ever want to apply the restriction to all JS libraries on your site.

Another solution for this- if you can handle it- is via server side scripting, specifically, .htaccess. Let's look at that now.