2

Hope this jquery based simple code will help to explain the issue.

html:

<script> 
  $('#remover').click(function(){
   $('#block').empty();
  })
  $('#test').click(function(){
   alert(remove1);  // still displays the varibale
  })
</script>
<div id="block">  
 <script>
    var remove1 = 'asasdsds';
    var remove2 = 'asasdsds';
    var remove3 = 'assdsdsdas';         
    var blabla = 'blablabl';
 </script>
</div>

<span id="remover">Remove ALL</span>
<span id="test">Test</span>  // it will still displays the variable.

I need to clear all variables from global scope by removing the block content. The block content is dynamic and can contain any javascript code.

Thanks for reading.

2 Answers 2

7

This certainly won't work as you expect. The JavaScript heap is not coupled to the DOM - once scripts have executed, and mutated the heap, you can't "unexecute" them by removing their associated source code.

Global variables are typically set on the window object, so if you know the names, you can remove them from there. If you want to undo the effects of any JavaScript inside the block, you're pretty much out of luck.

Sign up to request clarification or add additional context in comments.

2 Comments

I got it. i will try other ways then. Thanks for your info!
var declarations will add properties to the scope object (in <script> that's the global object) with the DontDelete attribute -- eg. once they're declared they can't be removed (although you can set them to null/undefined)
4

Javascript doesn't work that way! Once a script block is parsed, removing it from the DOM won't do anything... The only thing I can think of is a really ugly hack like this:

<script>
var blockKeys = [];
var oldKeys = {};
for (var i in window)
    oldKeys[i] = true;
</script>
<div id="block">  
 <script>
    var remove1 = 'asasdsds';
    var remove2 = 'asasdsds';
    var remove3 = 'assdsdsdas';         
    var blabla = 'blablabl';
 </script>
</div>
<script>
for (var i in window)
{
    if (!oldKeys[i])
        blockKeys.push(i);
}
alert(remove1);
</script>

Then your remove function looks like:

<script>
function remove()
{
    for(var i = 0; i < blockKeys.length; i++)
        eval(blockKeys[i] + ' = null');
}
</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.