I did some tests in Firefox 3 comparing the value of .src
and .documentWindow.location.href
in an iframe
. (Note: The documentWindow
is called contentDocument
in Chrome, so instead of .documentWindow.location.href
in Chrome it will be .contentDocument.location.href
.)
src
is always the last URL that was loaded in the iframe without user interaction. I.e., it contains the first value for the URL, or the last value you set up with Javascript from the containing window doing:
document.getElementById("myiframe").src = 'http://www.google.com/';
If the user navigates inside the iframe, you can't anymore access the value of the URL using src. In the previous example, if the user goes away from www.google.com and you do:
alert(document.getElementById("myiframe").src);
You will still get "http://www.google.com".
documentWindow.location.href
is only available if the iframe contains a page in the same domain as the containing window, but if it's available it always contains the right value for the URL, even if the user navigates in the iframe.
If you try to access documentWindow.location.href
(or anything under documentWindow
) and the iframe is in a page that doesn't belong to the domain of the containing window, it will raise an exception:
document.getElementById("myiframe").src = 'http://www.google.com/';
alert(document.getElementById("myiframe").documentWindow.location.href);
Error: Permission denied to get property Location.href
I have not tested any other browser.
Hope it helps!
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…