Tuesday 26 October 2010

Cross - Domain Scripting and iFrames

I've been doing some work over the last couple of days to embed data from a third party API into the .NET web app front end that we're working on. The API isn't open to everyone - you have to access it via Javascript and it can only be accessed on the server that all the component parts run on. As API's go it's pretty useless when you want to hook into it from somewhere else.

So our javascript guru showed me how to make an app in an iframe talk to the parent app that's hosting the iframe and away I went. I built a .jsp page on the API server that delivers all the data I want and then modified the .aspx page to include some labels to display the data.

I ran into a couple of problems. The first concerns the iframe load time. I originally tried to write some javascript that would load the values from the divs on the .jsp page into server controls on the .aspx page but this failed because the iframe was always the last thing to load and all the server controls saw was NULL values.

The js guru suggested a kind of timer function that would check when the iframe had finished loading before running a script to get the values. But it turned out that the simplest solution was to make the .jsp page populate the values itself - you can make the content of the iframe control what gets written to the screen in the parent as much as you can do it the other (and more logical) way around. In this case the connotation of parent and child is wrong - they're more like siamese twins joined together and able to influence each others movements.

Another useful thing to know is that you can only make two apps on two different servers talk to each other if you suffix the server name in the URL with the name of the domain that they both share. So if my domain is www.markp3rry.com then you will need to set the servers to http://server1.markp3rry.com:8080/ and http://server2.markp3rry.com:8090/ (for example).

There's a heck of a lot of scuttlebut written on the web about this topic so tread carefully. A lot of the examples for extracting information from an iframe in both javascript and jquery script were making me tear my hair out. You have been warned!

No comments: