Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 883
Marian Theisen Avatar asked Sep 14 '11 14:09

Marian Theisen


1 Answers

Can you try using postMessage?

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

like image 158
Khanh TO Avatar answered Oct 16 '22 15:10

Khanh TO