我有以下代码
<iframe src="http://www.w3schools.com" id="abc">
<iframe src="http://www.w3schoolss.com" id="abcd">
</iframe>
</iframe>
我想获取子 iframe 的 src 值。我无法获取该值。我什至使用
document.getElementById("abcd")
还有。但运气不好...
通过仅使用 javascript,我需要解决方案。
提前致谢...
最佳答案
`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/';
如果用户在 iframe 内导航,您将无法再使用 src 访问 URL 的值。在前面的例子中,如果用户离开 www.google.com 而你做了:
alert(document.getElementById("myiframe").src);
你仍然会得到“http://www.google.com”。
documentWindow.location.href
仅在 iframe 包含与包含窗口位于同一域中的页面时可用,但如果它可用,它始终包含 URL 的正确值,即使用户在 iframe 中导航。
如果您尝试访问 documentWindow.location.href
(或 documentWindow
下的任何内容)并且 iframe 所在的页面不属于包含窗口,它将引发异常:
document.getElementById("myiframe").src = 'http://www.google.com/';
alert(document.getElementById("myiframe").documentWindow.location.href);
尝试在 iframe
中比较 .src
和 .documentWindow.location.href
的值。 (注意:documentWindow
在 Chrome 中称为 contentDocument
,因此在 Chrome 中它不是 .documentWindow.location.href
,而是 。 contentDocument.location.href
.)
关于javascript - 获取子 iframe src 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26099697/