0

I'm serving a javascript file from my server. How do I prevent direct linking to it so that the server doesn't get used to serve the javascript to other websites?

1
  • Why would you want to do that?
    – Guidhouse
    Mar 25, 2011 at 7:27

3 Answers 3

3

The usual techniques for blocking hotlinking apply.

1
  • Yes, but there are some Javascript techniques as well, like Martin's answer.
    – Flimm
    Aug 27, 2015 at 12:27
3

To discourage hotlinking you could put annoying code in the script and have that execute if window.location doesn't match your own site:

while (window.location.hostname !== 'www.example.com')
  alert('Plz stop hotlinking');
2
  • but that would still serve the file and consume my bandwidth.
    – sami
    Mar 25, 2011 at 8:20
  • 1
    @sami yes, but you would render the script unusable to others and nobody in their right mind would link to it.
    – Martin
    Mar 25, 2011 at 9:23
1

There is no good way to do so. However, you could do some referer checks or check the values from the location object and make the JavaScript do bad things when embedded from a different site.

When doing referer checks don't forget to allow an empty referer as some people block referers.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.