Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: how to inject external html file ? (on same domain)

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 ?

like image 486
KJW Avatar asked Aug 27 '26 00:08

KJW


1 Answers

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

  }());
like image 164
Dagg Nabbit Avatar answered Aug 29 '26 13:08

Dagg Nabbit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!