bl4ckbox bl4ckbox - 4 years ago 178
Javascript Question

Load javascript only for specific domain?

I want the javascript loaded only on the domain that I specify, while if it is loaded by another domain, the page will be directed to the domain that I specify.

for example, I have a page in domain

mydomain.com
with some javascript there, then someone copy that javascript from my page and load it in
hisdomain.com
. Because I have set the script to function only in the domain
mydomain.com
, so the script will not work in
hisdomain.com
. Besides, it would be better if
hisdomain.com
redirected to
mydomain.com
.

I want to use this method to avoid theft and cloning scripts by people who are not responsible.

Thank you!

Answer Source

I want the javascript loaded only on the domain that I specify, while if it is loaded by another domain, the page will be directed to the domain that I specify.

This should do it:

if (location.host != "your.domain") location.href = "http://your.domain";

I want to use this method to avoid theft and cloning scripts by people who are not responsible.

That line will only help against the case that the other domain includes your.domain/script.js (and steals your bandwidth). When the script is actually copied (and not served from your server), it would be trivial to remove such a line. It's impossible to protect. Rather have a look at How can I obfuscate(protect) JavaScript?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download