Anthony Simmon
Anthony Simmon

Reputation: 1607

How to prevent cross domain javascript loading with .htaccess?

The company which developped my website just added this javascript code on the Zend Guard encrypted index.php file (I saw it with "View source") :

(function ()
{
    var smrs = document.createElement("script");
    smrs.type = "text/javascript";
    smrs.async = true;
    smrs.src = document.location.protocol + "//www.domain.com/file.js";
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(smrs, s);
})();

It injects a very agressive javascript code which adds a image link to their website (with a SetInterval each 10sec), at the bottom of the page.

The problem ? A local competitor, which is currently being accused of significant fraud, have the same CMS and the same image link.

Being associated with that competitor is prejudicial for me. I would like to know if there is a way to block the "www.domain.com/file.js" loading with a .htaccess.

Thanks.

Upvotes: 0

Views: 1262

Answers (1)

VDP
VDP

Reputation: 6420

You can't (using htaccess). This javascript creates a script tag to load the external javascript. The call never passes through the server. So apache (htaccess) can't block that.

The easiest way is to search in the source code and remove the script (if you have access).

UPDATE:

I see the script is encrypted... If you can insert a script at the very beginning (before the code gets executed you can create a hook on the insertBefore method. Here is a working fiddle

var ALLOWED_DOMAINS = ['www.klaartjedevoecht.be', 'jsfiddle.net'];
function creatHook(){
    function getDomain(url) {
       return url.match(/:\/\/(.[^/]+)/)[1];
    }
    var insertBefore = Element.prototype.insertBefore;
    Element.prototype.insertBefore = function(new_node,existing_node){
        if(new_node.tagName.toLowerCase() === 'script' && ALLOWED_DOMAINS.indexOf(getDomain(new_node.src)) > -1){
            insertBefore.call(this, new_node, existing_node);
        }
    }
}
creatHook();

//TESTING CODE:

var smrs = document.createElement("script");
    smrs.type = "text/javascript";
    smrs.async = true;
    smrs.src = document.location.protocol + "//www.klaartjedevoecht.be/test.js";

//var smrs = document.createElement("img");
//    smrs.src= "http://img52.imageshack.us/img52/7653/beaverl.gif";

var s = document.getElementsByTagName("div")[0];
    s.parentNode.insertBefore(smrs, s);

​I agree it's a bit hacking, but at least its cleaner then the timer solution. If you can't remove it, there is no clean solution.

Upvotes: 2

Related Questions