addEventListener( "load" ) 在 <iframe> Firefox 中使用时的问题



我有一个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

有几种方法可以解决这个问题:

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

  • 只有在表单上看到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有点新,但如果需要,可以很容易地填充。(

最新更新