使用 JQuery 获取 Iframe 的当前 src
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/748727/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting the current src of an Iframe using JQuery
提问by Micah
I need to get notified whenever a user clicks a link on a page in an iframe that is not from the same domain. I'm aware of xss restrictions, however all i need to know is the current page being served in the Iframe. Is there a way to do this without violating xss rules?
每当用户单击来自不同域的 iframe 中页面上的链接时,我都需要收到通知。我知道 xss 限制,但是我需要知道的是 Iframe 中提供的当前页面。有没有办法在不违反 xss 规则的情况下做到这一点?
采纳答案by joshuapoehls
If not for cross-site scripting restrictions this should work. Unfortunately I don't know of a way to get the URL without violating these restrictions.
如果不是跨站点脚本限制,这应该可以工作。不幸的是,我不知道如何在不违反这些限制的情况下获取 URL。
<html>
<head>
<script type="text/javascript">
function GetIFrameUrl()
{
alert('url = ' + document.frames['frame1'].location.href);
}
</script>
</head>
<body>
<a href="#" onclick="GetIFrameUrl();">Find the iFrame URL</a>
<iframe name="frame1" src="http://www.google.com" width="100%" height="400"></iframe>
</body>
</html>
回答by user237119
To get the iframe location using jQuery:
使用 jQuery 获取 iframe 位置:
alert( $('iframeId').contents().get(0).location.href );
回答by raam86
You can easily do it with vanilla js.
您可以使用 vanilla js 轻松完成。
- Query the document for an element with the specific name, id, class or whatever
Get the source for attribute for that element
//Get by Id var frame_src = document.getElementById('myIframe').src //Get by tag name - get the first var frame_src = document.getElementsByName('frmExternal')[0].src //Alert alert(frame_src)
- 查询具有特定名称、ID、类或其他任何元素的文档
获取该元素的属性来源
//Get by Id var frame_src = document.getElementById('myIframe').src //Get by tag name - get the first var frame_src = document.getElementsByName('frmExternal')[0].src //Alert alert(frame_src)
回答by sandeep kumar
<script type="text/javascript"> // if window open in iframe then redirect to main site
if(window.top.location != window.self.location)
{
alert(window.self.location);
// top.window.location.href = window.self.location;
}
</script>