How can I hide JavaScript's behavior from the user when I prohibit printing? I was able to prevent the print button from being pressed on that web page by writing the following inside the head tag of the html file:
<script type="text/javascript">
document.onkeydown = keys;
function keys()
{
switch (event.keyCode)
{
case 82: // Ctrl R
if( event.ctrlKey )
{
event.keyCode = 0;
return false;
}
case 80: // Ctrl P
if( event.ctrlKey )
{
event.keyCode = 0;
alert('Hello.'); //If this code was none, Ctrl and P can be executed,
return false;
}
break;
}
}
</script>
This Ctrl P is strange. If I do not intervene something before
return false;
such as
alert();
the print screen will appear.
However like
case 82: // Ctrl R
if( event.ctrlKey )
{
event.keyCode = 0;
return false; //without alert codes,this code can be executed.
}
The script can be executed without alert codes.It is strange thing for me.
If an alert message is seen, the user will easily see that it is running in JavaScript or something, so if possible, I want something invisible to the user side; What should I do? Do I have to show alert message to user like:
alert('Please do not print.');
I want some help.Thanks.
CodePudding user response:
If you want to prevent the user from printing the page and hide the fact that you are using JavaScript to do this, one way to do this is to use the window.onbeforeprint and window.onafterprint event handlers. These event handlers allow you to detect when the user is trying to print the page and then cancel the print operation before it starts.
Here is an example of how you might use these event handlers to prevent the user from printing the page without showing any alert messages:
// Handle the "beforeprint" event, which is triggered when the user
// tries to print the page
window.onbeforeprint = function() {
// Cancel the print operation
window.print = function() {};
}
// Handle the "afterprint" event, which is triggered when the user
// finishes printing the page
window.onafterprint = function() {
// Restore the default print behavior
window.print = function() {
// Call the default print function
window.print.call(this);
}
}
In this example, the onbeforeprint event handler cancels the print operation by replacing the window.print function with an empty function. This prevents the user from printing the page, but does not show any alert messages.
The onafterprint event handler restores the default print behavior by replacing the window.print function with a new function that calls the default print function. This allows the user to print the page again if they want to.
CodePudding user response:
The simplest and most standard way to implement this is with Event#preventDefault
:
window.addEventListener('keydown', (e) => {
if (e.key === 'p' && e.ctrlKey) {
e.preventDefault()
}
})