Sự kiện onafterprint kích hoạt sau khi hộp thoại in đóng (người dùng in xong hoặc hủy). Dùng để: khôi phục layout, xóa watermark, ghi log, bật lại UI bị ẩn khi in.
Ví dụ
<!DOCTYPE html>
<html>
<body onafterprint="display()">
<script>
function display() {
alert("In xong hoặc hủy in!");
// document.body.classList.remove('printing');
}
</script>
</body>
</html>
Cặp sự kiện in
| Sự kiện | Thời điểm | Dùng cho |
|---|---|---|
| beforeprint | Trước khi mở hộp thoại in | Chuẩn bị layout in, ẩn sidebar, thêm header/footer |
| afterprint | Sau khi đóng hộp thoại in | Khôi phục layout, cleanup |
Cách hiện đại
window.addEventListener('beforeprint', () => {
document.body.classList.add('printing');
});
window.addEventListener('afterprint', () => {
document.body.classList.remove('printing');
});
CSS @media print (khuyên dùng chính)
@media print {
.sidebar, .nav, .ads, .no-print { display: none !important; }
.content { width: 100%; margin: 0; }
a::after { content: " (" attr(href) ")"; font-size: 0.8em; color: #666; }
@page { margin: 2cm; } /* Margin trang in */
}
Lưu ý
- Mobile: hỗ trợ yếu, ưu tiên CSS print.
afterprintcũng chạy khi user hủy in (Esc/Cancel).