javascript - 在 Firefox 中与 <iframe> 一起使用时出现 addEventListener ("load") 问题

标签 javascript html firefox iframe ecmascript-6

我有一个 iframe,它是 form 的目标。当按下 submit 时,iframe 应删除 main 元素。这在除 Firefox 之外的所有主要浏览器中都按预期工作,其中 main 在页面加载时立即删除。

这只是 Firefox 中的一个错误,还是我遗漏了什么?

<小时/>

document.addEventListener("DOMContentLoaded", _ => {
  
  // Create an iframe and submit a form to it
  // ========================================

  const form = document.forms[0]
  form.setAttribute("target", "Response")

  const iframe = Object.assign(document.createElement("iframe"), {
    name: "Response"
  })
  iframe.hidden = true
  document.body.appendChild(iframe)

  iframe.addEventListener("load", () => {
    const main = document.querySelector("body > main")

    main.remove()

    iframe.hidden = false
  })
})
<main>
  <form action=https://script.google.com/macros/s/AKfycbzz-KveHder1A3CX8GcqZI6GR2MQj66PDRWNKoatIET_LXNqQs/exec method=get>
    <fieldset>
      <legend>Foobar</legend>
      <label><input type=radio name=Foobar value=Foo>Foo</label><br>
      <label><input type=radio name=Foobar value=Bar>Bar</label><hr>
      <input type=submit value=Submit>
    </fieldset>
  </form>
</main>

最佳答案

听起来,当空白 iframe 加载而其他 iframe 未加载时,Firefox 会触发 load

我想到了几种解决这个问题的方法:

  • 您可以检查 iframe位置,以确保它是您所期望的

  • 只有在表单上看到 submit 事件后,您才能设置 load 处理程序。 submit 事件肯定会发生在与之相关的 load 之前,因为 submit 发生在表单提交之前。

对我来说,第二种方法似乎是正确的选择。

<小时/>

重新使用位置,粗略地说(参见评论):

iframe.addEventListener("load", () => {
  // *** Only process the event if the iframe's location is the expected origin
  if (String(iframe.contentWindow.location).startsWith("https://script.google.com")) {
    const main = document.querySelector("body > main")

    main.remove()

    iframe.hidden = false
  }
})

(startsWith 有点新,但如果需要的话很容易填充。)

关于javascript - 在 Firefox 中与 &lt;iframe&gt; 一起使用时出现 addEventListener ("load") 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60344800/

相关文章:

javascript - 使用 javascript 更改 Google One Tap 登录位置

javascript - 在 Apps 脚本函数中获取 html 文本框的值

javascript - 直到动画完成后才应用 CSS3 透视图

firefox - Selenium 在 "Launching Firefox..."停止,没有错误或异常

javascript - 在发送到客户端之前乱码 JavaScript 代码

javascript - 只接受季度 float

javascript - 如何通过 Google Chart API 使用 csv 文件?

javascript - 在 jquery 中选中复选框时启用确认框按钮

firefox - 如何仅在打开开发者工具时关闭 Firefox 中的缓存?

javascript - parentNode 在 Firefox 中返回一个 window 对象,在 Chrome 中返回一个 div 对象