处理Chrome在Angular中的右键打印



我正在使用angular创建一个项目。当用户点击右键打印时,我想停止右键打印预览并初始化一些代码。

Here is Code

const mediaQueryPrint = window.matchMedia('print');
mediaQueryPrint.addListener(this.mediaQueryPrintListener.bind(this));
mediaQueryPrintListener(mql: MediaQueryList) {
if (mql.matches) {
// code runs
}else{
window.close()
}
}

问题是打印预览打开了,我想停止打印预览

您的代码不可能停止浏览器的功能。如果有人需要你网站上的内容,他们甚至可以截图。但是,您可以使用媒体查询'print'来阻止您的网站内容被打印。

,

@media print{
body {
display: none!important;
visibility: none!important;
}
}

这将在打印预览中显示空白屏幕。同样,你也可以通过隐藏其他内容来显示你的自定义消息。

,

In HTML
<div id="print-alert">Could not print this page</div>
<div class="not-print"><--YOUR CONTENT--></div>
In CSS
@media screen{
#print-alert{
display: none;
}
}
@media print{
#print-alert{
display: block;
}
.not-print{
display: none!important;
visibility: none!important;
}
}

这将只在打印预览中显示打印警告,而不是在实际站点中显示。同样,实际内容也被隐藏。

也可以使用javascript窗口提醒用户。提示如下:

ngOnInit(){
window.onbeforeprint = () =>{
window.alert("This page could not be printed"); //your message
}
}

通过使用这个,当用户试图使用浏览器打印预览时,它将提醒用户。

最新更新