0

I'm making a client side page builder which can let user load the script into the DOM and remove it back.

The problem is - although user remove the script element from the DOM, the variables are still available inside the DOM.

When user re-add the script again, it causes this error.

"Identifier '*' has already been declared"

How to clear old variables and avoid this error?

ronaldtgi
  • 687
  • 8
  • 17

1 Answers1

1

You can wrap the user's code in an IIFE (Immediately Invoked Function Expression) to avoid them from "polluting" the global namespace with consts of their own devising.

That is, if the user enters (your example)

const test = () =>{
  console.log('hello')
}
test();

then wrap it as

(() => {
  const test = () =>{
    console.log('hello')
  }
  test();
}())

and that test remains within the IIFE.

However, this will not help with e.g.

a = 9;

which would still implicitly assign a into the global (window namespace), whether or not IIFE'd.

AKX
  • 152,115
  • 15
  • 115
  • 172
  • This fixes the issue but a little work for me that I have to wrap all input scripts from users. Any better option for it? – ronaldtgi Jul 30 '21 at 11:13
  • 1
    Not that I can think of. But isn't wrapping your users' scripts just, you know, `script = '(() => {' + script + '}())'` before you plonk it into the DOM? Not that much work. – AKX Jul 30 '21 at 11:17