如何从iframe本身访问iframe进入父窗口?

时间:2018-04-07 19:38:51

标签: javascript html5 iframe

我有一个这样的顶级文档(顶部和iframe是相同的来源):

    <html>
    <body>
    <iframe class="loaded" src="https://www.example.com/article/645114"/>
    <iframe class="loaded" src="https://www.example.com/article/184789"/>
    <iframe class="loaded" src="https://www.example.com/article/4325"/>
    <iframe class="loaded" src="https://www.example.com/article/32586"/>
    </body>
    </html>

如果脚本在https://www.example.com/article/4325中运行,我想知道:

"This is running from frame 3"

https://www.example.com/article/645114中运行的相同脚本将返回:

"This is running from frame 1"

我该怎么做?

谢谢

1 个答案:

答案 0 :(得分:1)

在iframe中运行的脚本中尝试以下操作:

var loadeds = top.document.querySelectorAll('.loaded');
for(var i = 0; i < loadeds.length; i++){
    var src = loadeds[i].getAttribute('src'),
        this_url = document.URL;

    if(src === this_url){

        console.log('This is running from frame ' + (i + 1) + ' with the src attribute as ' + this_url);

        // Alternatively you could use.
        // alert('This is running from frame ' + (i + 1) + ' with the src attribute as ' + this_url);
    }
}

没有尝试过,但是如果你在上面的HTML结构的iframe中运行这个脚本,你应该得到一个控制台消息,告诉你脚本运行的是哪个帧。