Alternatives to iframe srcdoc?

后端 未结 3 1489
无人共我
无人共我 2020-12-14 03:29

Generally I am against the use of iframes, but it solved a particular problem of mine.

The thing is that I have a tinyMCE-editor at a webpage. After the user have ma

相关标签:
3条回答
  • 2020-12-14 03:35

    You can write to the document of an iframe like this:

    const html = '<body>foo</body>';
    const iframeDocument = document.querySelector('iframe#foo').contentDocument;
    const content = `<html>${html} </html>`;
    iframeDocument.open('text/html', 'replace');
    iframeDocument.write(content);
    iframeDocument.close();
    
    0 讨论(0)
  • 2020-12-14 03:41

    As suggested by eicto by comment, jquery could be used to fill an iframe at the ready-event. In order to adjust the height of the iframe to the height of the content some dirty hacks had to be applied, but the code I ended up using is more or less:

    HTML

    <!-- IMPORTANT! Do not add src or srcdoc -->
    <!-- NOTICE!    Add border:none to get a more "seamless" integration -->
    <iframe style="border:none" scrolling="no" id="myIframe">
        Iframes not supported on your device
    </iframe>
    

    JS

    // Wait until iFrame is ready (body is then available)
    $('#myIframe').ready(function() {
    
        var externalHtml = '<p>Hello World!</p>';
    
        // Find the body of the iframe and set its HTML
        // Add a wrapping div for height hack
        // Set min-width on wrapping div in order to get real height afterwords
        $('#myIframe').contents().find('body')
            .html('<div id="iframeContent" style="min-width:'+$('body').width()+'px">'
                +externalHtml
                +'</div>'
        );
    
        // Let the CSS load before getting height 
        setTimeout(function() {
            // Set the height of the iframe to the height of the content
             $('#myIframe').css('height', 
                 $('#myIframe').contents()
                 .find('#iframeContent').height() + 'px' 
             );
        },50);
    });
    
    0 讨论(0)
  • 2020-12-14 03:46

    Use the new Data URI Scheme. Example:

    var content = "<html></html>";
    document.getElementById("my_iframe_id").src = "data:text/html;charset=UTF-8," + content;
    0 讨论(0)
提交回复
热议问题