I'm creating an iframe dynamically like this:
let code = "<html><head><title> hello world <\/title><\/head><body><h1> hello world <\/h1><script>const h1 = document.querySelector('h1'); h1.style.color = 'red'<\/script><\/body><\/html>"
const iframe = document.createElement('iframe')
document.body.appendChild(iframe)
const content = iframe.contentDocument || iframe.contentWindow.document
content.open()
content.write(code)
content.close()
then later I change it's contents like this:
code = "<html><head><title> bye world <\/title><\/head><body><h1> bye world <\/h1><script>const h1 = document.querySelector('h1'); h1.style.color = 'red'<\/script><\/body><\/html>"
content.open()
content.write(code)
content.close()
but I get the following error: SyntaxError: redeclaration of const h1
because of the JavaScript being injected into the iframe.
is there someway to clear the global variable scope within the iframe before i write new code to it? I've tried iframe.contentWindow.location.replace('about:blank')
as well as iframe.src = 'about:blank'
but this doesn't clear it's internal JS variable scope. (I get the same error)
I realize I could trash the entire iframe and make a new one, but I'm going to be replacing the code a couple of times a second and I'm hoping for a less costly approach to update it.