I am writing a JavaScript pixel that will be served with AD creative on publisher pages. This AD will be contained in a cross domain iframe (sometimes many levels) on a publisher 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 an advertiser wants to know on what all pages his / her AD is getting served then we need to know the host page url.
As mentioned here we can get the parent page url using document.referrer like this
var url = (window.location != window.parent.location) ? document.referrer: document.location;
but it works only for the domain which is just one level up. We cannot reach till the topmost level since we do not have any control on "domain1.com" iframe. This is one problem which people are trying to solve for a long and there are many questions already on SO that asks exactly the same. But I am asking it again because of this article. It claims that they have a patented solution that can detect top level window url. Here is an excerpt from the blog
The lifesaver was a technique developed at AdSafe: The key to the solution was the ability to read the address of the top frame that was hosting the ad(*). We were detecting porn because the ads that were supposed to appear within a "clean publisher" site were appearing within the frame of a porn website. Think of HGTV as an illustrative, but not the real, example of such a "clean publisher."
So, is there a way to detect the top level window url ?
Similar Question: Top window's URL form inside of multiple nested cross-domain iFrames
If you are on the same domain, you can access the top frame by using
window.top.location.href
That's the easy answer.
If your nested iframe is on a different domain than your top domain, then you will run into the same origin policy problem, which is that frames hosted on different domain cannot communicate which each other for security reasons.
If you control the creation of the nested frame, one workaround is to pass a query string parameter pointing to your nested frame.
Another way is to use HTML5 postMesssage to communicate between the frames, but again, that requires that you have control on both domains.
Hope that helps.
I have a solution for you to get the domain in both Chrome and Opera, (in multiple nested cross-domain iframes), though unfortunately it is not possible in other browsers.
You can use the 'window.location.ancestorOrigins' property.
This snippet of code will work cross browser to get the closest possible page URL for you: https://gist.github.com/ocundale/281f98a36a05c183ff3f.js
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With