我目前正在使用:
function printThing(){
let link = parent.document.getElementById("oLink").href;
console.log(link);
}
if (window.attachEvent) {window.attachEvent("onload", printThing);}
else if (window.addEventListener) {window.addEventListener("load", printThing, false);}
else {document.addEventListener("load", printThing, false);}
从 iframe 的内容中获取链接(使用 srcdoc 而不是 src)并将其打印在控制台中。此代码将在发送到前端之前添加到一些存储的 html 中。
有没有办法在 iframe 内容加载后触发此操作(即无需等待应用程序中的其他内容)?我尝试用 document
替换所有 window
但它不起作用(它什么也不做)。
我需要从 iframe 内部访问元素并更改它们的属性。
最佳答案
HTML
此方法仅使用 onload
属性在加载框架内容后调用该函数。
<iframe id="some_frame" onload="on_iframe_load(this)">
....
</iframe>
显然,请确保您的 JS 代码中有 on_iframe_load(_this)
函数。
为了进一步解释为什么我们将 this
传递到 on_iframe_load()
中,请理解从 DOM 元素传递 this
将传递对该元素的引用。
<script>
var on_iframe_load(_this) = () => {
_this.contentDocument.getElementById("something_in_this_frame").doWhatever(...);
}
</script>
纯JS
如果 HTML
无法让您的船漂浮,您可以使用 onload
或 addEventListener("load", ...)
,然后使用元素指针和 contentDocument
访问 iframe
内的元素(没有 IE?)
<script>
document.getElementById("some_frame").onload = function() { // or you could use `addEventListener("load", function(){...})`
this.contentDocument.getElementById("some_element_in_frame").doThing(...)
}
</script>
关于javascript - 如何在加载 iframe 内容后立即运行函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56873792/