appendChild dataURI image to window.open failing i

2019-09-06 13:05发布

问题:

I am trying to grab an image from an interactive map using dataURI. That image is then appended to a new window layout for printing.

This works in Firefox and Chrome but not in IE11 or Edge which both throw errors. IE: "HierarchyRequestError" Edge: "No such interface supported"

This question is very similar but unanswered and the offered solutions relate to objects other than image data.

I suspect this method might work but i can't figure out how to implement it properly for a URI.

Current code working in FF and Chrome;

function screen(){

var simg = new Image();
var dataURL = map.getCanvas('#map').toDataURL();

simg.src = dataURL;

var mywindow = window.open('about:blank','Print','height=800,width=900');
var is_chrome = Boolean(mywindow.chrome);

mywindow.document.write('<!DOCTYPE html><head>');
mywindow.document.write('<link rel="stylesheet" href="./css/scr.css" type="text/css" />');
mywindow.document.write('</head><body>'); 
//add logos and legend here.
mywindow.document.write('</div></body></html>');
mywindow.document.body.appendChild(simg);

        if (is_chrome) {
            setTimeout(function () { 
                    mywindow.document.close();
                    mywindow.focus(); 
                    mywindow.print();  
                    mywindow.close();
            }, 600);
        } else {

    mywindow.document.close(); 
    mywindow.focus(); 
    mywindow.print();
    mywindow.close();       

    }
    return true;    
}

回答1:

This was resolved by setting the body innerHTML using the image outerHTML as suggested here.

    try{
    mywindow.document.body.appendChild(simg);
    }
    catch(e){
    if (simg.outerHTML) {
    mywindow.document.body.innerHTML = simg.outerHTML;
    }
    else {
    //console.log('not working');
    }
    }