Getting top frame URL

In the facebook application, I need to check what the top frame (main window) is and show the 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 the iframe, but when the page loads in the iframe (as when using it as a facebook application), the code generates

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

Is there a way to fix this code (with compatibility between browsers - possibly with jQuery)?

Thanks!

Joel

+4
source share
5 answers

The problem you are facing is that you are not allowed access to top.location for different document domains.

This is a security feature built into browsers.

Read the XSS and why there are precautions :)

You can also learn a lot by reading the same origin policy.

+6
source

It is true that cross-origin issues will not allow you to access this location of the top window. However, if you just want the location of the parent iframe to be obtained using the string document.referrer .

In your iframe, you grab the URL:

var parentURL = document.referrer

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

I have successfully used this application in my iframe applications. Also, keep in mind that if you move inside your iframe, the referrer will change.

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

+8
source

With Martin Jespersen, the recommended fix, I could check the address in iFrame and the standard 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 } 
+3
source

This might work:

 if (self!=top && document.referrer.toLowerCase().indexOf("facebook.com") <0) { ... } 

... until you move inside the frame.

But this is not a good solution ^^

+1
source

Have you tried this:

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

Source: https://habr.com/ru/post/1338503/


All Articles