javascript css在chrome中打印时隐藏页面url(但仍显示页码)

javascript css在chrome中打印时隐藏页面url(但仍显示页码),javascript,html,css,google-chrome,printing,Javascript,Html,Css,Google Chrome,Printing,当用户尝试打印网页时,我想隐藏浏览器添加到打印页面的所有额外细节,但仍然只显示页码 像这样: 我使用以下CSS代码成功地隐藏了它们: @page{ size: A4; margin: 8mm; } @page{ size: A4; margin: 8mm 8mm 9mm; } 或者只有前2个,使用以下CSS代码: @page{ size: A4; margin: 8mm; } @page{ size: A4;

当用户尝试打印网页时,我想隐藏浏览器添加到打印页面的所有额外细节,但仍然只显示页码

像这样:

我使用以下CSS代码成功地隐藏了它们:

@page{
    size: A4;
    margin: 8mm;
}
@page{
        size: A4;
        margin: 8mm 8mm 9mm;
}
或者只有前2个,使用以下CSS代码:

@page{
    size: A4;
    margin: 8mm;
}
@page{
        size: A4;
        margin: 8mm 8mm 9mm;
}

但打印页面时隐藏url结构并没有达到我的目标。

根据设计,您不能触摸浏览器打印对话框

当您使用
@page{margin:8mm}
时,默认页边距会变小,所有额外的细节都会消失,因为它们没有位置

因为页码和页面url都位于页面底部-您不能只显示或隐藏其中一个,但是,您可以在显示打印对话框之前更改页面url,并在打印结束后将其更改回,这样打印的页面就不会显示url结构

//custom function to fire when print dialog is closed
function afterPrintOver (){
    console.log('Print is over.');
    //remove our empty state
    window.history.back();
}

//detect when the user is click `Ctrl + P` to print
document.addEventListener('keydown', function(e){
    const PKeyCode = 80;
    if( e.ctrlKey && e.keyCode === PKeyCode ){
        //stop the browser from open the print dialog
        event.preventDefault();

        //add an empty state, the url now will be www.yourDomainName.com/#/print
        window.history.pushState('', '', '#/print');

        //call our afterPrintOver function, and 'pass' the result of `window.print()`*
        afterPrintOver(window.print());
});
事情就是这样:

  • 用户按CTRL+P组合键
  • 我们使用自定义相对url将空状态添加到历史记录中
  • 浏览器的“打印”对话框显示自定义url
  • 打印结束(或用户关闭打印对话框)
  • 我们删除空状态,这将把url更改回正确的url

  • *诀窍是我们的
    afterPrintOver
    函数在
    窗口关闭之前不会启动。print()
    函数将关闭并返回
    未定义的
    ,这意味着打印过程结束。

    如果有人使用鼠标打印或使用带有“打印”的键盘怎么办关键?一个更可持续的方法可能是指导用户在他们的设置中取消对页眉/页脚的锁定:无论如何,没有办法跨浏览器可靠地控制它。@BenjaminGruenbaum很棒的一点,我没有想到……谢谢@Elad很不错,但不幸的是,它现在在chrome版本90.0.4430.212(官方版本)(64位)中不起作用。我和你一样被困在同一个问题上。我想打印页码,但我不想要其他详细信息,如URL、标题和日期。我开始发布答案,然后找到答案