Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

i know i can't access data in an iframe which displays a page from another domain. thats perfectly fine. but i'd like to detect, wether the iframe currently shows a page from my domain or something external.

my first attempt would be to try to access

$('iframe')[0].contentWindow.document

wrapped in try {} catch {}, and if an error is thrown, it means, i can't access it, and therefore the iframe page must be external. this sounds like a perfect solution, but the thing is, safari posts a "Unsafe JavaScript attempt to access frame with URL" to the javascript console. this is not just ugly, but may cause other or future browsers to display explicit security warnings to the user?

share|improve this question
1  
Your solution seems perfectly valid. Pay no attention to the noise from Safari, which is not visible to end-users. – danorton Sep 14 '11 at 14:19
Incidentally, you’ll also get warnings in the Safari console when you load www.apple.com. Warnings are not generally anything to worry about (although they can be very annoying and, IMHO, should be something that the console should allow you to filter.) – danorton Sep 14 '11 at 14:29
thanx, i'll leave it as that for now. – Marian Theisen Sep 14 '11 at 14:35

3 Answers

If this is your HTML:

<iframe src="http://www.google.com" width="100%" height="300" id='iframe'>
  <p>Your browser does not support iframes.</p>
</iframe>

wouldn't it be just that simple:

var iframeEl = document.getElementById('iframe')
var src = iframeEl.src;

and then use it to compare to your domain?

share|improve this answer
1  
src always returns the initial value, but the iframe page will definitely change due to following links / submitting a form within the iframe – Marian Theisen Sep 14 '11 at 14:30
Should still be enough to know whether it is on the same domain, unless you somehow end up on your own domain by following some link inside the iframe, the initial value should do, no? Is it even possible? – ZenMaster Sep 14 '11 at 14:42

Why not check if the href attribute from the iframe is the same as your domain?

parent.frames[1].location.href;
share|improve this answer

Can you try using postMessage?

If there is no response, it is an external domain.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.