Chrome中的打印功能不再有效

Jef*_*mon 5 javascript google-chrome window.open

我们的网站有一个功能,可以打印成员个人资料.它的工作方式是通过onsubmit将javascript函数附加到按钮.javascript函数使用window.open以特殊模式重新打开页面,该模式重新显示页面的打印机友好版本.

此功能自2008年左右开始实施,适用于所有浏览器.除了大约一周前,它已停止在Chrome中工作.使用Chrome,会发生打开的窗口打开,但随后会打开另一个空白窗口,然后全部关闭.

在搜索这个问题的讨论时,我无法找到确切的问题,但确实找到了一些内容,表示应该在onsubmit中添加"return false".我尝试添加,但它没有帮助.

这是onsubmit的样子:

<button onclick="PrintEmailSubmit('print');">Print Profile</button>
Run Code Online (Sandbox Code Playgroud)

以下是打开窗口的代码:

window.open('print-email-profile.php?mode=' + mode,'','width=' + width + ',height=' + height + ',scrollbars=yes,location=0,menubar=1,status=0,toolbar=0')
Run Code Online (Sandbox Code Playgroud)

虽然没有必要看,这里是整个函数PrintEmailSubmit():

/*
 *  called by view-profile.php
 */
function PrintEmailSubmit(mode)
{
    var width;
    var height;
    switch(mode)
    {
        case 'print':
            width = 850;
            height = 1000;
            break;

        case 'email':
            width = 400;
            height = 120;
            break;

        default:
            alert('Error: invalid calling sequence -- should not happen!');
            exit;
    }
    window.open('print-email-profile.php?mode=' + mode,'','width=' + width + ',height=' + height + ',scrollbars=yes,location=0,menubar=1,status=0,toolbar=0');
}
Run Code Online (Sandbox Code Playgroud)

最后,使这项工作的原因是页面的特殊版本在body标签中添加了以下内容:

<body onload="window.print();window.close();">
Run Code Online (Sandbox Code Playgroud)

如上所述,该功能继续在IE和Firefox中运行.只是Chrome有这个问题.

有任何想法吗?

Lum*_*ack 6

按钮和window.open实际上与您的问题无关.

问题是,Chrome在打印之前正在寻找用户输入.Window.print()打开打印对话框窗口,但Chrome不等待您完成打印.window.close()正在关闭打印对话框窗口以及父窗口中的所有其他内容.

为了节省您的时间,请注意Chrome根本不使用OnAfterPrint挂钩.我还尝试将window.close()放在onLead和onBeforeUnload中的window.print()中,但print对话框取消了window.close().接下来最好的事情是做一些事情:

//In your profile print page
<html>
<head>
<script>
var is_chrome = function () { return Boolean(window.chrome); }
if(is_chrome) 
{
   window.print();
   setTimeout(function(){window.close();}, 10000); 
   //give them 10 seconds to print, then close
}
else
{
   window.print();
   window.close();
}
</script>

<body onLoad="loadHandler();">
Run Code Online (Sandbox Code Playgroud)

我没有对此进行测试,但我认为它可以相当有效地展示这个想法.

  • 接下来,为什么不将setTimeout放到window.close中呢?但是,这不起作用。setTimeout必须存在,但可以很短。我现在有200,或者说0.2秒,它工作正常。也就是说,它允许该功能像过去一样在Chrome上运行,打印对话框只是无限期地等待用户输入,并且没有延迟关闭窗口。我不明白,但是可以。实际上,相同的代码也可以在其他浏览器上使用,从而可以简化最终形式。仅将setTimeout添加到原始代码似乎足以解决该问题。 (2认同)
  • 最终解决方案:使用以下内容代替原始正文onload:&lt;body onload =“ window.print(); setTimeout(function(){window.close();},200)”&gt; (2认同)