Main Page Content
Restricting Access To Your Javascript Libraries
Restricting access to JavaScriptlibraries to designated domains
libraries allow us to separate script from page, so multiple pages can allutilize the same script simply by linking to it:<script src="greatscript.js"></script>
Just to refresh our memories, "myscript.js" should contain the
script itself minus the surrounding <script></script> tags, andsaved as a text file (but with .js extension).Now, the nature of JS libraries means that they're not only accessible by
your site/domain, but anyone's. Like an image, a library could potentially beutilized by any site that decides they like your script but not the bandwidthassociated with it. Specifically, they would simply use a syntax like thefollowing on their page:<script src="http://www.yourdomain.com/greatscript.js"></script>
This can become a headache, especially if the library is very large.
Using JavaScript to restrict access to 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 locationfield of the browser, through the propertydocument.location.href//returns the URL in the location field of browser
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 knowthe library is being accessed from an outside source (and take appropriateaction). Suffice it to say such a code will need to be added directly inside thelibrary 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" filevar accepted_domains=new Array("wsabstract.com","javascriptkit.com")var domaincheck=document.location.href //retrieve the current URL of user browser
var accepted_ok=false //set acess to false by defaultif (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 foundaccepted_ok=true //set access to true, and break out of loopbreak}}}elseaccepted_ok=trueif (!accepted_ok){
alert("You're not allowed to directly link to this .js file on our server!")history.back(-1)}/////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.hrefto get the current URL of the user's browser. Now we have both of our keywitnesses 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 thetwo, and only allow the library to proceed "loading" if there is amatch (if one of accepted_domain's values is contained within domaincheck). Thisis 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 ofthis is so that offline accessing of the JavaScript library is left out of thescrutinization process- obviously there's no point in restricting access of alibrary when it's accessed offline, especially if you want to be able to testthe library out on your hard drive!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 toyour library. Then there's the repetitious work involved if you ever want toapply the restriction to all JS libraries on your site. Another solution forthis- if you can handle it- is via server side scripting, specifically,.htaccess. Let's look at that now.Using .htaccess instead for the task
In the tutorial Comprehensive
Guide to .htaccess, it featured a magical little file called .htaccess ofyour server (you may or may not have access to it, depending on your web host),and how it can enable everything from custom 404 pages, password protection ofdirectories, to disabling hot linking of images on your server. Well, faced withour current challenge, we simply need to elaborate on that last point a bit, soinstead of- or apart from- images, JavaScript libraries are included within thelist of files not to be accessed from outside your site.Take a look at the below code, which is all that's needed to accomplish the
task using .htaccess:RewriteEngine onRewriteCond %{HTTP_REFERER} !^$RewriteCond %{HTTP_REFERER} !^http://(www\.)?wsabstract.com/.*$ [NC]RewriteCond %{HTTP_REFERER} !^http://(www\.)?javascriptkit.com/.*$ [NC]RewriteRule \.(js gif jpg)$ - [F]
Notice "js" in the last line, which adds .js files, along with .gif
and .jpg to the type of files only the domains listed above can access. The codeshould be saved inside your .htaccess file, and dropped into your web pagedirectory.