javascript - 在通过 child.print() 打印之前,如何等待图像加载到新窗口中?

标签 javascript printing popup parent-child onload

    $("#print").on('click', function () {
        var child = window.open("image.jpg", "_blank", "location=0,toolbar=0,scrollbars=1,fullscreen=1,menubar=0");
        //any way to know/wait for image to load?
        child.print();
    });

有什么方法可以让我的父窗口在调用 .print() 之前知道子窗口已完成加载图像吗?如果他们高兴的话,他们最终会打印一张空白页。

我都尝试过:

child.attachEvent("onload", function () { child.print(); });

child.attachEvent("DOMContentLoaded", function () { child.print(); });
//(found this online, apparently it's Firefox only, still didn't work)

最佳答案

您需要创建一个页面,即 print.html 并向其中添加以下脚本:

<html>
<head>
</head>
<body>
<script>
(function( w, d ) {
    var paramsHash = {},
        img = new Image(); 

    (function() {
        var qs = w.location.href.split( '?' )[ 1 ],
            items = [],
            l = 0,
            i = 0,
            param;
        if( qs && qs.indexOf( '&' ) ) {
            items = qs.split( '&' );
        } else {
            items = [ qs ];
        }
        l = items.length;
        for( ; i < l; i++ ) {
            param = items[i].split( '=' );
            paramsHash[ param[ 0 ] ] = param[ 1 ];
        }
    })();
    console.log(paramsHash);
    img.src = paramsHash.img;
    //after the image is loaded, call this function
    img.onload = function() {
        window.print();        
    };
    d.body.appendChild( img );

})( window, document );
</script>
</body>
</html>

然后像这样使用它:

$("#print").on('click', function () {
    window.open("print.html?img=image.jpg", "_blank", "location=0,toolbar=0,scrollbars=1,fullscreen=1,menubar=0");
    });

关于javascript - 在通过 child.print() 打印之前,如何等待图像加载到新窗口中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12359150/

相关文章:

javascript - 如何使用reactjs从响应中获取数据(如数组格式)

javascript - 双击 td 时如何在警告框中将数据库中的数据显示为 html 表

html - Internet Explorer 9 中的 SVG 打印

c - 如何在 unix 上以 C 图形方式打印到控制台

php - 仅向用户显示一次警报

javascript - 如何使用在 getScript 回调函数内生成的 URL 打开一个新窗口,并避免弹出窗口拦截器?

javascript - 为什么 chrome 不为嵌入式 twitter 时间轴呈现 flexbox 定位?

javascript - 如何使用 JS/React 在点击时复制链接 ID?

html - Firefox 为@page 指令增加了 5mm 的额外边距

javascript - 小书签如何避免弹出窗口拦截器