2014-01-31 51 views
0

有什麼方法可以捕獲瀏覽器的打印事件並取消打印對話框的外觀?避免使用javascript瀏覽器打印對話框

例子:

User clicks in "File" -> "Print". 
Before the print dialog appears, show a confirm() like 'It is possible that not all data is printed, continue anyway? <accept> <cancel> 
User clicks <accept> -> Print dialog appears 
User clicks <cancel> -> Print dialog doesn't appear 

現在我有這樣的:

var beforePrint = function(ev) { 
if (!messageShown) { 
    var result = confirm('Are you sure?'); 
    if (!result) { 
    // TODO: Cancel 
    } 
} 
}; 
var afterPrint = function(ev) { 
    // TODO 
}; 

if (window.matchMedia) { 
    var mediaQueryList = window.matchMedia('print'); 
    mediaQueryList.addListener(function(mql) { 
    if (mql.matches) { 
     beforePrint(); 
    } else { 
     afterPrint(); 
    } 
    }); 
} 

window.onbeforeprint = beforePrint; 
window.onafterprint = afterPrint; 
+2

沒有現代瀏覽器將允許您*防止*打印功能。正確如此。 – CodingIntrigue

+0

@Rraham:他們可能會提供某種類似OP所需的確認框,例如'beforeunload'事件會;但你是對的 - 他們不會爲'打印'。 – Bergi

+1

如果您有佈局問題,請嘗試專門的打印樣式表,它幾乎隱藏了除您的數據之外的所有內容。 – Gant

回答

0

你不需要取消。如果他們點擊接受,請致電window.print()。如果他們使用cntrl-p或文件 - >打印,無論如何編程方式超出了你的控制。順便說一句,應該指出,你實際上無法做任何事情來阻止用戶手動嘗試打印。這包括攔截他們嘗試產生對話並阻止它顯示。您可以做的最好的做法是將樣式表應用於默認打印,然後動態更改該打印樣式表,以便在使用代碼進行打印時啓用內容的可見性。

+1

你*可以*攔截'Ctrl + P' – CodingIntrigue

+0

你可以添加一些例子嗎? –