简体   繁体   中英

JavaScript: How to retrieve document object of HTML object tag?

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.

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

HTML5中不推荐使用Object元素,因此您将无法再使用它。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM