Getting iframe content's height while iframe i

2019-03-01 05:52发布

问题:

Possible Duplicate:
to fit iframe to its content height

As is described in the title of the question. I'm looking for a way to adjust the height of my iframe according to the height of the website that my iframe is hosting. Because I need to get rid of the vertical scroll of my iframe. And at the same time, I don't want to set a very huge static height to my iframe, as this is not nice when I have pages with small heights.

I've found many solutions related to my problem, but can't solve my problem:

(*) Changing the iframe's height while iframe is hosting an internal page is easy. You just add the following script to your iframe onload event:

        var frame = (document.getElementById) ? document.getElementById("YourFrameID") : document.all["YourFrameID"];
        var pageh = document.frames("YourFrameID").document.body.scrollHeight;
        frame.style.height = pageh + 'px';

But as would you know, when the src of the iframe is outside the domain that has the iframe. the script crashes, and produces 'Access denied' error message.

(*) Finally, I know that my goal can be achieved if I have access to the pages that my iframe is hosting. Perhaps the technique is called "Cross-Domain Communication".

HOWEVER, my iframe is aiming to host pages from EXTERNAL websites, and there is NO access to those websites.

This question has been asked many times. Let's get rid of this issue by providing one final answer :)

Or.. let's say that achieving my specific goal is not applicable.

Note that I use ASP.NET 4.0

Thanks,

回答1:

It is simply not possible due to the cross domain security reasons.



回答2:

You could use the man-in-the-middle technique. Instead of pointing the iframe directly at the intended target, point it at a page on your server that:

  1. Retrieves the requested URL and injects the script.

  2. Rewrites images and other resources that have relative URL's to use absolute URL's that point to the source.

This is messy and error-prone.

Alternatively, if you have some sort of HTML renderer on the server, you could retrieve the document, parse it, and query for the height. This is messy, slow, error-prone, and not cross-browser compatible.

I think the real answer you are looking for is, no, there is no reliable way to achieve this effect without cooperation from the cross-domain resource.