清除iframe内容(包括它的JS全局范围)你好世界<\/title><\/head><body><h1>你好世界<\/h1><scri...</desc> <question vote="4"> <p>我正在像这样动态创建一个 iframe:</p> <pre><code>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() </code></pre> <p>然后我将其内容更改为这样:</p> <pre><code>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() </code></pre> <p>但我收到以下错误:<pre><code>SyntaxError: redeclaration of const h1</code></pre>,因为 JavaScript 被注入到 iframe 中。</p> <p>在向 iframe 写入新代码之前,有什么方法可以清除 iframe 内的全局变量范围吗?我已经尝试过 <pre><code>iframe.contentWindow.location.replace('about:blank')</code></pre> 以及 <pre><code>iframe.src = 'about:blank'</code></pre> 但这并不能清除它的内部 JS 变量范围。 (我也遇到同样的错误)</p> <p>我意识到我可以废弃整个 iframe 并创建一个新的 iframe,但我将每秒更换几次代码,并且我希望有一种成本更低的方法来更新它。</p> </question> <answer tick="false" vote="0"> <p>您可以用花括号 <pre><code>const</code></pre> 将动态 <pre><code>let</code></pre> 变量中的 <pre><code>content</code></pre> 和 <pre><code>{}</code></pre> 声明括起来,创建块作用域。这是解决重新声明错误的简单方法。</p> <pre><code>// Note the added braces {} within the <script> 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>" </code></pre> <p>可能更好的方法是首先删除 DOM 中已存在的所有 iframe,然后在需要添加内容时重新创建 <pre><code>iframe</code></pre>。</p> <pre><code>const updateIframe = (code) => { const iframe = document.createElement('iframe') document.body.querySelector('iframe')?.remove() document.body.appendChild(iframe) const content = iframe.contentDocument || iframe.contentWindow.document content.open() content.write(code) content.close() } </code></pre> </answer> </body></html>

问题描述 投票:0回答:0
javascript variables iframe scope
© www.soinside.com 2019 - 2024. All rights reserved.