[英]'afterprint' event not firing on first page load in Chrome
當通過頁面上的按鈕打開打印對話框時,我有一個頁面需要隱藏一些元素。 下面粘貼了代碼的基本功能。 Chrome 是此項目所需的瀏覽器,不支持或不允許使用其他瀏覽器。
問題是 'afterprint' 事件沒有在頁面的第一次加載時觸發。 如果我刷新頁面,代碼會按預期運行。 重現的步驟是:
奇怪的是,如果我隨后刷新頁面,代碼會按預期工作。 另一件奇怪的事情是,如果我只是雙擊 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.