Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting URL of the top frame

Inside a facebook application I need to check what is the top frame (the main window) URL, and show content accordingly.

I tried using the following:

if (top.location.toString().toLowerCase().indexOf("facebook.com") <0) { ... }

Which works well if the page is not inside an iframe, but when the page is loaded within an iframe (as it does when used as facebook application) the code generates

"Uncaught TypeError: Property 'toString' of object # is not a function".

Is there any way I can fix this code (with cross-browser compatibility - maybe with jQuery)?

Thanks!

Joel

like image 836
Joel Avatar asked Feb 04 '11 21:02

Joel


3 Answers

It is true that cross origin concerns will prevent you from accessing this top window location. However, if you just want the parent window location of the iframe you can get at it via the document.referrer string.

Within your iframe you'd grab the url:

var parentURL = document.referrer

https://developer.mozilla.org/en-US/docs/Web/API/document.referrer

I've used this successfully in my own iframe apps. Also, be aware that if you navigate within your iframe the referrer will change.

Nicholas Zakas has a write-up on his blog: http://www.nczonline.net/blog/2013/04/16/getting-the-url-of-an-iframes-parent/

like image 74
mcanfield Avatar answered Oct 18 '22 14:10

mcanfield


The problem you are having that you are not allowed to access top.location across different document domains.

This is a security feature built in to browsers.

Read up on XSS and why the security precautions are in place :)

You can also learn a great deal by reading about the same origin policy

like image 5
Martin Jespersen Avatar answered Oct 18 '22 14:10

Martin Jespersen


With Martin Jespersen adviced fix, I could check address in iFrame and standart top address:

//this is fix for IE
if (!window.location.origin) {
    window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port: '');
    }

//and here we will get object of address
var urls = (window.location != window.parent.location) ? document.referrer: document.location;

//Martins adviced fix for checking if You are not in iFrame    
if (window.top === window) {
    urls = urls.origin;
}

//and now indexOf works in both ways - for iFrame and standart top address
if (urls.indexOf("facebook.com") != -1 ) {
   //do stuff
}
like image 3
Nick Bristol Avatar answered Oct 18 '22 14:10

Nick Bristol