Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 清除iframe内容(包括它的JS全局范围)_Javascript_Variables_Iframe_Scope - Fatal编程技术网

Javascript 清除iframe内容(包括它的JS全局范围)

Javascript 清除iframe内容(包括它的JS全局范围),javascript,variables,iframe,scope,Javascript,Variables,Iframe,Scope,我正在动态创建一个iframe,如下所示: let code=“hello world hello world const h1=document.querySelector('h1');h1.style.color='red'” 常量iframe=document.createElement('iframe') document.body.appendChild(iframe) const content=iframe.contentDocument | | iframe.contentWin

我正在动态创建一个iframe,如下所示:

let code=“hello world hello world const h1=document.querySelector('h1');h1.style.color='red'”
常量iframe=document.createElement('iframe')
document.body.appendChild(iframe)
const content=iframe.contentDocument | | iframe.contentWindow.document
content.open()
content.write(代码)
content.close()
后来我把它的内容改成这样:

code=“bye world bye world const h1=document.querySelector('h1');h1.style.color='red'”
content.open()
content.write(代码)
content.close()
但是我得到了以下错误:
SyntaxError:consth1的重新声明
,因为JavaScript被注入到iframe中

在我编写新代码之前,是否有办法清除iframe中的全局变量范围?我尝试了
iframe.contentWindow.location.replace('about:blank')
以及
iframe.src='about:blank'
,但这并没有清除它的内部JS变量范围。(我得到了同样的错误)


我意识到我可以扔掉整个iframe并制作一个新的,但我将每秒更换几次代码,我希望更新它的成本更低。

我也有同样的问题,因为我正试图避免移动浏览器对每个iframe都要求一次mic权限的情况。所以我只想替换框架的内容,但遇到了相同的语法错误:重新声明。@nforss-dang,我没有想到这一点,但在我的用例中,我可能也会遇到同样的问题(因为我确实计划使用现在需要显式用户权限的API)。。。我真的希望有办法解决这个问题:(