grab global variable from an embedded iframe

2020-06-03 09:23发布

问题:

say an HTML page (Page.htm) contains the following...

<script type="text/javascript">
    var vara = 'varA';
</script>

Now this page is loaded into an iframe from another page with...

<iframe id="child_frame" src="http://mysite.com/Page.htm" />

From the parent page, I would like to get the value of the global 'vara' from Page.htm.

None of the following lines work...

    window.frames['child_frame'].window.vara;

    window.frames['child_frame'].window['vara'];

    window.frames['child_frame'].contentWindow['vara']; 
    // in fact contentWindow returns undefined!!

Any help would be appreciated!

UPDATE

After looking at this problem more, and trying the various libraries that are available to get around this issue, I had the epiphany that since I have IIS control over both the main and iframe embedded websites, I can work within the cross domain scripting rules by using the same base URL for the various websites. Also, the libraries that get around the problem appear to need constant updating as the browser vendors tighten their security with continuous updates. It would really be a chore to have to always be updating the workaround for circumventing what the browser is trying to keep you from doing.

回答1:

Your first syntax should work IF you're on the same doamin.

If the IFRAME is loading a page from another domain then you won't be able to access it.



回答2:

This:

<iframe id="child_frame" src="http://" />

Should be:

<iframe name="child_frame" src="http://" />

The iframe attribute "id" should be changed to "name".