【问题标题】:Problem with addEventListener("load") when used with <iframe> in Firefox在 Firefox 中与 <iframe> 一起使用时 addEventListener("load") 出现问题
【发布时间】:2020-06-06 05:54:48
【问题描述】:

我有一个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 应该替换主要元素...” 我没有看到 替换。我看到删除...?
  • @T.J.Crowder 你说得对!我使用了不好的术语。
  • @T.J.Crowder 我通过 JavaScript 设置了target 属性。
  • 哦……确实,它就在代码中。对不起。 :-D

标签: javascript html firefox iframe ecmascript-6


【解决方案1】:

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

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

  • 您可以检查 locationiframe 以确保它是您所期望的

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

对我来说,第二种方式似乎是要走的路。


重新使用location,粗略地说(见 cmets):

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 有点新,但必要时可以轻松填充。)

【讨论】:

  • 由于 Google Apps 脚本中的某些安全策略,我无法使用 submit 事件。我试过了。所以它必须使用纯 HTML 提交。您能否进一步扩展您的 location 建议?
  • @Tzar - 如果表单在不使用 JavaScript 的情况下提交也没关系,但是有一个提交处理程序只是为了知道它已提交不应该是一个问题......?不过,我现在正在添加更多关于 location 的详细信息。
  • @Tzar - 完成。 :-)
猜你喜欢
  • 1970-01-01
  • 2011-07-10
  • 2015-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多