:::: MENU ::::
Posts tagged with: javascript

iframe communication on different domains, Facebook App example

You have a Facebbok App. When you go to that app you have a Facebook page and your app is embedded via iframe.

Later on it turns out that within your code you have an iframe with something, lets say some kind of form but in different domain. And you have a problem, because due to Same Domain Origin Policy you can’t talk between those iframes. There is a nice solution for that.

You can use a friendly helper from main domain that is embedded in forms iframe, as 3rd level you’d say.

So the main idea is to change iframe src if you form file, where you can embed this helper.

Take a look on this brief schema.

Code

facebook.html

<html>
	<body>
		<p>FACEBOOK</p>
		
		<iframe src="http://domain-a.com/app.html" style="width: 500px; height: 300px;"></iframe>
	</body>
</html>

http://domain-a.com/app.html

<html>
	<body>
		<p>YOUR FACEBOOK APP</p>
		
		<iframe src="http://domain-b.com/form.html" id="form"></iframe>

		<script type="text/javascript">
			function redirect(url){  
			    window.location.href = url;
			}
			 
			function resize() {
			    document.getElementById('form').height = 500;
			}
		</script>
	</body>
</html>

http://domain-b.com/form.html

<html>
	<body>
		<iframe id="helper" src="" width="0" height="0" ></iframe>
		 
		<p>EXTERNAL FORM</p>
		 
		<a onclick="redir();">REDIR</a>
		<a onclick="resize();">RESIZE</a>
		 
		<script type="text/javascript">
			function redir() {
			    var helper = document.getElementById('helper');
			    helper.src = "http://domain-a.com/iframeparent/helper.html?action=redir";
			}
			 
			function resize() {
			    var helper = document.getElementById('helper');
			    helper.src = "http://domain-a.com/iframeparent/helper.html?action=resize";
			}
		</script>
	</body>
</html>

http://domain-a.com/iframeparent/helper.html

<html> 
	<body onload="start();">
		<script type="text/javascript">
			function start(){
			    var action = getParam('action');
			     
			    if (action =='redir') {
			        parent.parent.redirect('http://www.onet.pl/');
			    } else if (action == 'resize') {
			        parent.parent.resize();
			    }
			}
			 
			function getParam( name )
			{
			  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
			  var regexS = "[\\?&]"+name+"=([^&#]*)";
			  var regex = new RegExp( regexS );
			  var results = regex.exec( window.location.href );
			  if( results == null )
			    return "";
			  else
			    return results[1];
			}
		</script>
	</body>
</html>

source: Resizing an iframe based on content