我有一个 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 中与 <iframe> 一起使用时出现 addEventListener ("load") 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60344800/