0

I try to call document.open/write/close sequence inside object element (type="text/html"). In Safari/Chrome I'm able to grab the inner document object by contentDocument attribute. Sample code (using jquery):

$(document).ready(function() {
  var container = $('<object/>')
    .css({'width': '700px', 'height': '100px', 'border': '0px none'})
    .attr({'type': 'text/html'}).appendTo('body');

  var doc = container.get(0).contentDocument;
  doc.open();
  doc.write('<h1>Hello world!</h1>');
  doc.close();
});

Is there any way to do the same in other browsers?

The reason I want to do such odd thing is my need to call external scripts containing document.write after the DOM is closed. I've already tried dealing with iframes, but due to Internet Explorer and Opera bugs I failed. Any other way to achieve this goal will be appreciated.

ptkoz
  • 2,388
  • 1
  • 20
  • 28
  • What bugs? And is the src of the object initially same origin? – mplungjan Mar 26 '13 at 18:05
  • http://stackoverflow.com/questions/1736886/why-wont-this-javascript-using-document-open-and-document-write-work-in-inter Bobince comment explains bugs. IE9 is still affected and can eventually crash. – ptkoz Mar 26 '13 at 18:15

2 Answers2

1

This should work for you. I don't know why (I only have my suspicion).

$(document).ready(function () {
    var container = $('<object>')
        .css({
            'width': '700px',
            'height': '100px',
            'border': '0 none'
        })
        .attr({
            'type': 'text/html',
            'data': 'about:blank'
        })
        .appendTo('body');

    function writeToDoc() {
        var obj, doc;
        obj = container.get(0);
        if (obj.document) {
            doc = obj.document;
        } else if (obj.contentWindow) {
            doc = obj.contentWindow.document;
        }
        else if (obj.contentDocument) {
            doc = obj.contentDocument;
        }
        if (doc) {
            doc.open();
            doc.write('<h1>Works!</h1>');
            doc.close();
        } else {
            $('body').append('<h1>No luck...</h1>');
        }
    };

    // yes, this is weird
    setTimeout(writeToDoc, 0);
});
mYsZa
  • 505
  • 3
  • 12
1

Object element is deprecated in HTML5 so you won't be able to do it anymore.