ManticMoo.COM All Articles Jeff's Articles
Jeffrey P. Bigham

How to disable Javascript using Javascript

Jeffrey P. Bigham

Related Ads

This article deals with how to disable javascript by somewhat circularly employing javascript itself. I'm not sure why you'd want to do this, but I bet some people would. It also provides an excellent demonstration of recursive Javascript programming and of accessing elements in the DOM.

The script works by starting at the topmost html element and recursively working through all other elements on the page. This only removes script tags (and the text/code between them) and the onClick event attribute present in tags. There are obviously extensions you could make that would make it handle more.

You might be inclined to wonder what happens to code that is removed while the code itself is running. In my experiments, I've see that nothing happens - it seems that browsers keep a local copy of code while running it and this isn't updated until after the code finishes running.

 
 
<html>
<script>
function traverseDomTree() {
  var html_element = document.getElementsByTagName("html").item(0);
  traverseDomTree_recurse(html_element);
  alert("done");
}
 
function traverseDomTree_recurse(curr_element) {
  var my_string = "";
 
  if(curr_element == null) {
    return;
  }
 
  if(curr_element.nodeName == "SCRIPT") {
    curr_element.setAttribute("src", "");
    curr_element.innerHTML = "";
    return;
  } else if(curr_element.nodeName == "#text") {
    return;
  }
 
  curr_element.setAttribute('onclick', '');
 
  var i;
  for(i=0; curr_element.childNodes.item(i); i++) {
    traverseDomTree_recurse(curr_element.childNodes.item(i));
  }
}
 
</script>
<body>
 
<a href="#" onClick="alert('hello');">Click Here</a>
 
<br>
 
<input type="button" onClick="traverseDomTree();">
 
</body>
</html>
 

And that's all there is to it! You've successfully stripped out all of the javascript code contained in <script> tags as well as all onclick events. You've also hopefully learned a little about Javascript and the DOM as well.

Jeffrey P. Bigham
ManticMoo.COM All Articles Jeff's Articles