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?
Asked
Active
Viewed 7.5k times
4 Answers
40
To get the iframe location using jQuery:
alert( $('iframeId').contents().get(0).location.href );

Jason Aller
- 3,541
- 28
- 38
- 38

user237119
- 409
- 4
- 4
-
1this doesn't work for me – knocte Mar 25 '12 at 23:23
-
8this works only in the case of a same domain -- xss security prevents it for different domains – Alvin Nov 30 '13 at 20:49
-
Note, if the js is running *inside* the iframe, selecting the iframe like that won't work, but selecting it like "$('iframe', window.parent.document)" does. (Still assuming the same domain.) – neminem May 12 '15 at 17:40
9
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.
<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>

joshuapoehls
- 32,695
- 11
- 50
- 61
-
3Yes, it does. I don't believe there is a way to do what you need without violating the rules. – joshuapoehls Apr 15 '09 at 05:40
-
2
-
1This is a nice answer, but the asker requested a jQuery solution, not plain JavaScript. – Mr. Lance E Sloan Aug 14 '13 at 20:14
-
@LS: true, but the reasonable question should be understood as "best practices way to do it with jQuery around?" ... and if this would mean to do it with plain JS it should be fine – Andreas Covidiot Nov 30 '16 at 21:56
5
You can easily do it with 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)

raam86
- 6,785
- 2
- 31
- 46
1
<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>

Sandeep Sherpur
- 2,418
- 25
- 27