簡體   English   中英

“后印”事件未在 Chrome 中加載第一頁時觸發

[英]'afterprint' event not firing on first page load in Chrome

當通過頁面上的按鈕打開打印對話框時,我有一個頁面需要隱藏一些元素。 下面粘貼了代碼的基本功能。 Chrome 是此項目所需的瀏覽器,不支持或不允許使用其他瀏覽器。

問題是 'afterprint' 事件沒有在頁面的第一次加載時觸發。 如果我刷新頁面,代碼會按預期運行。 重現的步驟是:

  1. 在 Chrome 中導航到頁面
  2. 點擊打印按鈕
  3. 在打印對話框中單擊“取消”,“后印”事件不會觸發。

奇怪的是,如果我隨后刷新頁面,代碼會按預期工作。 另一件奇怪的事情是,如果我只是雙擊 html 文件並在 chrome 中打開,那么代碼會按預期工作。 當然,這是假設將 chrome 設置為用於打開 html 個文件的默認應用程序。 我可以在 Chrome 開發工具的 Sources 選項卡的 Global Listeners 中看到該事件已注冊,但它不會觸發。

<html>
<body>
<button id="print">Print</button>
<div id="prompt">
    Hide if print dialog is open
</div>
<script>

    document.getElementById('print').addEventListener("click", ev => {
        document.getElementById('prompt').style.display = 'none';
        window.print();
    })
    window.addEventListener('afterprint', ev => {
        console.log('After print')
        document.getElementById('prompt').style.display = 'block';
    })

</script>
</body>
</html>

任何幫助表示贊賞。 謝謝你。

我有這個完全相同的問題......當第一次點擊打印按鈕時,afterprint 事件監聽器沒有觸發......但是當我第二次點擊打印按鈕並且任何連續點擊都會觸發上述事件聽眾......我解決了這個問題如下

window.addEventListener('beforeprint', beforePrintFunction);
window.addEventListener('afterprint', afterPrintFunction);
window.print();
window.removeEventListener('beforeprint', beforePrintFunction);
window.removeEventListener('afterprint', afterPrintFunction);

這對我很有效...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM