Search This Blog

Wednesday, August 25, 2010

Show IFrame content in plain-text using javascript/jquery

Today i was working on a html page, wherein another page would be displayed in an iframe and the user gets an option to see the iframe's html. Using raw javascript it became bit confusing and i didn't get the desired result , so i switched over to my favorite jquery. Jquery fulfilled 2 of my requirements at once. First one was retrieving the code and second converting html characters to corresponding html character codes so that it shows up as text and not in rendered form. Next it would display the text in a textarea.

Note: Only content on local domain is accessible for security purpose, so it may not be possible to show html content of pages external to the local domain even though the page loads in iframe.

Key Components :
$.get(url,callback-function) : A get request for retrieving the iframe html page
$('textarea').text(data) : For html conversion

How it works :
On a click of the specified entity, the jquery makes a request for the desired page using $.post() function. The iframe source url is retrieved using $('iframe').attr('src'). $get(url,callback-function) in this case takes 2 arguments, the url will be the iframe location and callback-function is the function called on the event of success. The callback-function gets the received data as argument
In the callback-function we use $('textarea').text(data) to convert the received data to code form and set it as the content of textarea.

The Code :




No comments:

Post a Comment