Marian Theisen
Marian Theisen

Reputation: 6352

javascript: check if iframe url is same domain or something external

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?

Upvotes: 9

Views: 5191

Answers (3)

Khanh TO
Khanh TO

Reputation: 48982

Can you try using postMessage?

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

Upvotes: 1

kasper Taeymans
kasper Taeymans

Reputation: 7026

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

parent.frames[1].location.href;

Upvotes: 0

ZenMaster
ZenMaster

Reputation: 12746

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?

Upvotes: 0

Related Questions