views:

94

answers:

3

Hi,

Why I want to block a JS file download in HTML? Well, this is my time-chart for the page load:

  1. jQuery (1.2) loaded
  2. jQuery plugin loaded (extends the current jQuery object)
  3. custom JS loaded
  4. custom JS uses document.write to add extra scripts
  5. the added extra script loads a new jQuery (1.4, but it doesn't matter)
  6. -> so my extension is gone since it's a new jQuery object

What I can't do is to put (5) or (3) before (2). I'm working with Drupal (PHP framework) and these are contributed modules. I also can't parse the added script at point (3) because it uses document.write.

So I thought maybe I could deny the download of the 2nd jQuery script. Currently I've no other idea. But that might be impossible. What do you think?

A: 

What I can do is loading the jQuery extension (2) again, after (6). It works but it's not nice.

itarato
+1  A: 

No. Even if you somehow blocked a user from targeting your .js directly in a browser, it still gets downloaded to the computer's hard drive when the page is visited. Even if you somehow managed to keep the .js file from downloading to the visitor's hard drive, it still has to be resident in the memory of the computer. There is no way to protect your precious source code from prying eyes. Obfuscation makes it more difficult however.

The only solution I can think of is to have your web application render the screen, take a screen shot, and send the image to the visitor. Good luck with that.

Sparafusile
A: 

So, here's what I came up with:

Instead of preventing that JS I can put it into an iframe - that makes it a sandbox environment so it can't hurt anything else. Here you are: First the external script has to be parsed, because I pass it as a string:

function parse_str_to_js($txt) {
  $txt = str_replace('\\', '\\\\', $txt);
  $txt = str_replace('"', '\\"', $txt);
  $txt = str_replace("\r\n", '\n', $txt);
  $txt = str_replace("\n", '\n', $txt);
  $txt = str_replace('<', '\u003C', $txt);
  $txt = str_replace('>', '\u003E', $txt);
  return $txt;
}

Then in HTML instead of:

<php echo $advertisement_script; ?> 

should be replaced to a placeholder:

<div id="advertisement"></div>

And in JavaScript an iframe will be created:

$(function(){
  $('#advertisement').html('<iframe id="iframe_advertisement"/>');
  var advertisement = "<?php echo parse_str_to_js($advertisement); ?>";
  document.getElementById('iframe_advertisement').contentWindow.document.write(advertisement);
});
itarato