Search code examples
jqueryajaxhtmlpreview

how to make preview webpage application


I want to make a simple application having only one text field and a preview button.

It should display the preview of the page in a div on the same page. Please see the blow code to get exact idea.

    <form method="POST" action="" id="preview-form" >
        <input type="text" id="urltopreview" name="urltopreview" />
        <input type="button" id="preview-button" value="Preview">
        <div id="preview"></div>
   </form>

When I insert the URL and click Preview button, it should load the preview of that page in the div (having id="preview" ) using jquery & ajax.

I tried to use php function file_get_contents() to generate preview but I get broken images.

Any idea?


Solution

  • You can use an hidden Iframe and set it source to the url entered in the textbox. Then, get the content of the iframe and append it to you preview div.

    function getContentFromIframe(iFrameName)
    {
    
         var myIFrame = document.getElementById(iFrameName);
         var content = myIFrame.contentWindow.document.body.innerHTML;
    
         $("#preview").html(content);
    
    }
    

    OR

    To load an internal page: You can use the Jquery method load()

     $("#preview").load($('#urltopreview').val());
    

    This Jquery method will not work to load external pages because ajax calls cannot retrieve external pages for security reasons. The only way to get external pages onto your page is to use an iframe, or a server side proxy that you can call with your ajax.