JGilmartin
JGilmartin

Reputation: 9298

Scroll an iframe that contains a page from a different domain

I'm currently developing a clicktail clone. I've recorded all the mouse interactions and window scrolls and my plan is to play them back by opening the URL that has been recorded into an iframe and then have a mouse image move to the captured coordinates, images indicating when a click occurred and the iframe scrolling to the captured scroll positions

this was working nicely while I was viewing a page from my domain in the iframe, but as soon as I display a page from a different domain, I get access denied errors from the FF console and the same issues from IE

this is due to the Same origin policy for JavaScript.

I have been reading this article -> Ways to circumvent the same-origin policy

it seems that this is becoming an issue for many developers and there are hacks to get round it.

can anyone suggest a suitable hack for my situation ?

Upvotes: 1

Views: 2035

Answers (2)

Oliver Moran
Oliver Moran

Reputation: 5167

You could use a PHP proxy on your domain that (a) reads the target URL to a string, (b) adds a base tag so that images, links, etc. work correctly and then (c) prints the string.

The end result is a page that is identical to the page from the external domain but is hosted on your domain. This means that you can execute JavaScript in the child frame from the parent frame.

The code for the proxy is as follows:

<?php
    ini_set("user_agent", $_SERVER['HTTP_USER_AGENT']); // temporarily override CURLs user agent with the user's own

    $page = file_get_contents($_REQUEST["www"]);
    $page = preg_replace("/<[\s]*head[^>]*>/i", "<head><base href='".$_REQUEST["www"]."' /><base target='_blank' />", $page);
    echo $page;
?>

One consideration when using this method is that when the user (or JavaScript) clicks a link in the proxied page, the user will be taken to a page on the original domain (or elsewhere). This means that your JavaScript will no longer be able to access or execute scripts in the iframe.

To make this consequence more transparent, links are set to target='_blank' in the code above.

Upvotes: 1

mattsven
mattsven

Reputation: 23303

You could always fake it. Maybe you could have your place your iframe in a container div (css: overflow: hidden; height: /* some height */), with the iframe element set to the full height of the page, and scroll the div?

Upvotes: 1

Related Questions