3

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 ?

2
  • 1
    Is the file on a remote domain, or the same one as the current page? Commented Sep 22, 2010 at 0:03
  • same domain, so Single Origin Policy is not an issue. Commented Sep 22, 2010 at 0:10

2 Answers 2

2

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);

  }());
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.