javascript - 获取子 iframe src 值

标签 javascript html iframe

我有以下代码

<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/

相关文章:

javascript - 打印 HTML 页面(整页!)

html - 我怎样才能让某些字母在彼此上方直接对齐?

http - 如何限制 SAML 302 重定向到 IFRAME?

javascript - 创建脚本以将 Google Closure 用于多个 javascript 文件

javascript - 关于 "Tail Call Optimization"文章的问题

javascript - 如何在滚动时让一个元素 div 移动而另一个不移动?

jquery - 当像 jQuery 中的灯箱一样单击链接时,如何在动态生成的 iFrame 中加载页面?

javascript - 不允许将顶部框架导航到数据 URL : JsPDF

javascript - Postgres + Javascript + 时区

javascript - 如何在 Bootstrap 导航栏中放置按钮?