views:

86

answers:

2

I am trying to inject an external html file into the current DOM using javascript. This is on the same domain so Single Origin Policy is not an issue.

var body = document.getElementsByTagName('body')[0];
var script= document.createElement('p');
script.innerHTML = 'http://samedomain.com/my.html';
body.appendChild(script);

any ideas ?

A: 

For remote domains, you could use JSOP, same way as Gist does.

Eg: see http://gist.github.com/5710.js

For local you could use an ajax call to pull the html followed by document.write of the result.

Keep in mind, if its a straight html page, you may want to strip the head and html tags prior to injecting into the page.

Sam Saffron
+2  A: 

If it's on the same domain, you can use XmlHttpRequest (which works differently in different browsers) or simply append an invisible iframe to the document with a src attribute having the value of the page you want to load, and then get the iframe's document's body's parent element node object's innerHTML property (non-standard but widely supported).

If it's on a remote domain, the easiest way is to have your server fetch the page and then use one of the above approaches, as browsers protect against cross-domain scripting.

Here's a quick example of the hidden iframe approach; it should be the easiest to get working for all browsers:

  (function(){

    // our callback: do this when the remote document loads.
    function callback() {
      var b = frames['my_hidden_frame'].document.body;
      var response = (b.parentElement||b.parentNode).innerHTML;
      // do whatever you need to do here
      alert(response);
    }


    // create an iframe
    var e = document.createElement('iframe');

    // your ajax content
    e.src = '/some/local/path';

    // give the frame an id
    e.id = 'my_hidden_frame';

    // make the iframe invisible, but don't just display:none, 
    // because some browser (forgot which, old safari?) screws it up
    e.style.height='0px';
    e.style.width='0px';
    e.style.position='absolute';
    e.style.left='-100px';

    e.onload=callback;

    // put it in the body, it will load.
    document.body.appendChild(e);

  }());
no