我有一个iframe
,它是form
的目标。按下submit
时,iframe
应移除main
元素。这在除Firefox之外的所有主流浏览器中都能正常工作,在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
的location
以确保它是您所期望的 -
只有在表单上看到
submit
事件后,才能设置load
处理程序。submit
事件肯定会在与其相关的load
之前,因为submit
发生在表单提交之前。
对我来说,第二条路似乎就是路。
粗略地重新使用location
(见注释(:
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
有点新,但如果需要,可以很容易地填充。(