Accessing frameset element inside iframe

2019-08-14 07:23发布

问题:

I'm trying to access frame src attribute inside a frameset. But document.getElementById('cntvars').firstChild is null. How do I step into the child elements?

<iframe id="cntvars" onload="prstofrm();" src="http://sites.google.com" style="display:none"></iframe>
    <html>
        <head></head>
            <frameset rows="100%,*" border="0">
                <frame src="http://sites.google.com?qty=13.00&amp;sub=7.24&amp;shp=0.00&amp;dis=0.00&amp;vch=0.00&amp;tax=0.00&amp;tot=7.24&amp;sd=" frameborder="0">
                <frame frameborder="0" noresize="">
            </frameset>
            <!-- pageok -->
            <!-- 04 -->
            <!-- -->
    </html>
</iframe>

回答1:

You can't (unless you're working at Google and writing code for sites.google.com, which I assume you aren't). The same-origin policy prevents the parent page from "looking at" the contents of frames which are stored on other domains.



回答2:

To access the document element inside the frameset you can use

var iframeEl = document.getElementById('cntvars');
var iframeDoc = iFrameEl.document | iFrameEl.documentElement

http://xkr.us/articles/dom/iframe-document/

The most sure fire way to have it work with all browsers is to give a name to your frames and iframes and access it using window.frames['frameName'] which will point to that frame's window object. Also, you can refer to them by index, so if this was all the HTML for the page, you could use window.frames[0].frames[1] to access the empty frame inside your frameset