How to get parent iframe element from inner page without knowing id?

落爺英雄遲暮 提交于 2019-12-12 10:38:33

问题


Let's imagine that I have something like this:

<html>
...
    <div>
        <iframe src="test.html" hash="r4d5f7"></iframe>
        <iframe src="test.html" hash="8f7x97"></iframe>
        <iframe src="test.html" hash="gg4v5e"></iframe>
        <iframe src="test.html" hash="e54f87"></iframe>
    </div>
...
</html>

test.html is empty page, custom hash attribute always has a different value, both pages are on the same domain for security reasons, number and order of iframe elements is random.

My question is: Is there a way to get from inner page (test.html) using Javascript to its proper iframe element? Let's say, I'm in the third iframe's page and I need to get to its iframe element and alert() hash value (in this case "gg4v5e").

To be more specific. If you are familiar with Firefox's Firebug, it visualizes this situation like this:

<html>
...
    <div>
        <iframe src="test.html" hash="r4d5f7">
            <html>
                 ...
            </html>
        </iframe>
        <iframe src="test.html" hash="8f7x97">
            <html>
                 ...
            </html>
        </iframe>
        <iframe src="test.html" hash="gg4v5e">
            <html>
                 ...
            </html>
        </iframe>
        <iframe src="test.html" hash="e54f87">
            <html>
                 ...
            </html>
        </iframe>
    </div>
...
</html>

Is it possible to call "something" in order to get parent element (<iframe>) when I'm with my Javascript at <html> element in inner page?


回答1:


Sure there is. This code works in FF and IE6, Opera, Chrome (requires a web server and both files coming from same domain protocol and port)

        function getHash()   {
           var ifs = window.top.document.getElementsByTagName("iframe");
           for(var i = 0, len = ifs.length; i < len; i++)  {
              var f = ifs[i];
              var fDoc = f.contentDocument || f.contentWindow.document;
              if(fDoc === document)   {
                 alert(f.getAttribute("hash"));
              }
           }
        }


来源:https://stackoverflow.com/questions/3151665/how-to-get-parent-iframe-element-from-inner-page-without-knowing-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!