Determine top-level window URL from multilevel iframe cross-domain

I am writing a JavaScript pixel that will be used with AD ads on publisher pages. This AD will be contained in the cross-domain iframe (sometimes many levels) on the publisher’s site. So the publisher page looks like this

host (publisher) site

<html> <iframe src="http://domain1.com" name="first_level_iframe"> <iframe src="http://domain2.com" name="second_level_iframe"> <!--The script I want to write will be hosted here--> </iframe> </iframe> </html> 

If the advertiser wants to know on which pages all his ADs are processed, we need to know the URL of the main page.

As mentioned here , we can get the URL of the parent page using this document.referrer

 var url = (window.location != window.parent.location) ? document.referrer: document.location; 

but it only works for a domain that is just one level up. We cannot reach the very top level, since we have no control over the iframe "domain1.com". This is one of the problems that people have been trying to solve for a long time, and on SO there are already many questions that are asked in the same way. But I again ask for this because of this article . He claims that they have a patented solution that can detect the top-level URL of a window. Here is an excerpt from the blog

Rescuer is a technique developed at AdSafe: the key to the solution was the ability to read the address of the top frame, which was the advertisement placement (*). We are discovering porn because the ads that were supposed to appear on the "pure publisher" site appear within the porn website. Think of HGTV as a but not a real example of such a “pure publisher”.

So, is there a way to detect the top level url of a window?

Similar question: Upper window URL form inside multiple nested cross-domain iFrames

+5
source share
2 answers

I have a solution for getting a domain in both Chrome and Opera (in several nested cross-domain iframes), but, unfortunately, this is not possible in other browsers.

You can use the window.location.ancestorOrigins property.

This code snippet will work with a cross browser to get the maximum page URL for you: https://gist.github.com/ocundale/281f98a36a05c183ff3f.js

+1
source

If you are in the same domain, you can access the top frame using

 window.top.location.href 

This is an easy answer.

If your nested iframe is in a different domain than your upper domain, then you will encounter the same issue of origin policy, which is that frames located in different domains cannot communicate with each other for security reasons.

If you control the creation of a subframe, one way is to pass a query string parameter that points to your subframe.

Another way is to use HTML5 postMesssage to communicate between frames, but again, which requires that you control both domains.

Hope this helps.

+1
source

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


All Articles