admin管理员组

文章数量:1405369

I know I can't access data in an iframe which displays a page from another domain. That's perfectly fine, but I'd like to detect, whether 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" message to the javascript console. This is not just ugly, but may cause other or future browsers to display explicit security warnings to the user?

I know I can't access data in an iframe which displays a page from another domain. That's perfectly fine, but I'd like to detect, whether 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" message 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 edited Dec 7, 2016 at 12:14 rredondo 1,0661 gold badge17 silver badges23 bronze badges asked Sep 14, 2011 at 14:15 Marian TheisenMarian Theisen 6,35231 silver badges40 bronze badges 3
  • 1 Your solution seems perfectly valid. Pay no attention to the noise from Safari, which is not visible to end-users. – danorton Commented Sep 14, 2011 at 14:19
  • Incidentally, you’ll also get warnings in the Safari console when you load www.apple.. 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 Commented Sep 14, 2011 at 14:29
  • thanx, i'll leave it as that for now. – Marian Theisen Commented Sep 14, 2011 at 14:35
Add a ment  | 

3 Answers 3

Reset to default 1

Can you try using postMessage?

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

If this is your HTML:

<iframe src="http://www.google." 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 pare to your domain?

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

parent.frames[1].location.href;

本文标签: javascript check if iframe url is same domain or something externalStack Overflow