iFrame onload JavaScript事件

Pel*_*eke 29 javascript iframe onload onload-event dom-events

我有一个iFrame,我想在加载后发送JavaScript命令.我当前的代码如下所示:

<iframe src="http://www.test.tld/" onload="__doPostBack('ctl00$ctl00$bLogout','')">
Run Code Online (Sandbox Code Playgroud)

但是使用此代码,命令不会执行.我必须改变什么来使它工作?只支持Chrome和Firefox.

小智 36

使用iFrame的.onloadJavaScript功能:

<iframe id="my_iframe" src="http://www.test.tld/">
    <script type="text/javascript">
        document.getElementById('my_iframe').onload = function() {
            __doPostBack('ctl00$ctl00$bLogout','');
        }
    </script>
    <!--OTHER STUFF-->
</iframe>
Run Code Online (Sandbox Code Playgroud)


小智 8

你的代码是正确的。只需测试以确保它被调用如下:

<script>
function doIt(){
  alert("here i am!");
  __doPostBack('ctl00$ctl00$bLogout','')
}
</script>

<iframe onload="doIt()"></iframe>
Run Code Online (Sandbox Code Playgroud)


ant*_*ove 7

document.querySelector("iframe").addEventListener("load", function() {

  this.style.backgroundColor = "red";
  alert(this.nodeName);

});
Run Code Online (Sandbox Code Playgroud)
<iframe src="example.com" ></iframe>
Run Code Online (Sandbox Code Playgroud)

  • 这种添加“load”监听器的方式与设置 iframe.onload = a function 的其他答案有什么区别? (4认同)