Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removed JavaScript is still executable

Tags:

If I have the following JavaScript code:

<script id="someJS">      var boom = 'boom';      function example(){          alert(boom);     }  </script> 

and then do:

$('#someJS').remove(); 

I can still call example() even though that JavaScript function is no longer inside the DOM... How can I remove it?

I don't want to null the actual function(s) and variables with: boom = null; example = null; as I don't always know what is inside the JavaScript file. For example the function names, variables, etc. I need to be able to remove the entirity of what was inside that script tag.


Update: For those that wanted to know the user case for this:

Basically in an app I am working on, we have custom JavaScript added for certain clients that when a button is clicked e.g. save, then checks if certain functions exist and then runs them. However because this save button is generic it means that that the custom code gets called all the time after it's added even if it's no longer relevant.

The solution we have come up with (someone had posted this as an answer but they removed it for some reason) was to namespace it all like:

DynamicJS = {      boom: 'boom',      example: function(message) {          alert(message);      }  } 

And then we can just do: delete DyanmicJS;

Which removes all the functions and variables inside this namespace from the global scope, effectively binning off what the script file added.

Although I am sure this is not a perfect solution as if you had event listeners inside the file, I'm sure they would still exist!

like image 639
Cameron Avatar asked Apr 30 '15 14:04

Cameron


1 Answers

How can I remove it? I don't want to null the actual function, as I don't always know what is inside the JS file.

You can't. Script code is executed, creates things in the JavaScript environment, and is completely disconnected from the script element that loaded it. Other than completely reloading that environment, if you don't know what the code did, you can't undo it.

Even if you could infer some of what the code did (for instance, by making a list of globals before and after), while you could remove new globals you detected (or at least set them to null or undefined, since delete doesn't work wiith globals added via function declarations or var), that doesn't tell you what event handlers, web workers, etc. the code may have hooked up.

like image 122
T.J. Crowder Avatar answered Dec 09 '22 20:12

T.J. Crowder