How to trigger javascript on print event? - javascript

Is it possible to trigger a javascript event when a user prints a page?
I would like to remove a dependancy on a javascript library, when a user opts to print a page, as the library is great for screen but not for print.
Any idea how to achieve this?

For anyone stumbling upon this answer from Google, let me try to clear things up:
As Ajay pointed out, there are two events which are fired for printing, but they are not well-supported; as far as I have read, they are only supported in Internet Explorer and Firefox (6+) browsers. Those events are window.onbeforeprint and window.onafterprint, which (as you'd expect) will fire before and after the print job.
However, as pointed out in Joe's link (https://stackoverflow.com/a/9920784/578667), that's not exactly how it is implemented in all cases. In most cases, both events fire before the dialog; in others, script execution might be halted during the print dialog, so both events may fire at the same time (after the dialog has been completed).
For more information (and browser support) for these two events:
https://developer.mozilla.org/en-US/docs/DOM/window.onbeforeprint
https://developer.mozilla.org/en-US/docs/DOM/window.onafterprint
The short answer: if you're hoping to interfere with the print flow, don't. If you're hoping to trigger code after printing, it's not going to work how you're wanting; expect poor browser support, and try to degrade gracefully.

It can be done by overwriting, e.g., window.onbeforeprint.
Using Chrome, I found that the more arcane window.matchMedia("print").addListener(function() {alert("Print Dialog open.")}) also works.
This debatable feature can be used in order to deter users from printing a page.
I've encountered it the first time on Scribd. There, if you open the print dialog using the menu command, the page content will be greyed out and a warning pop-over message appears explaining why you can not print the page. (Note for complete analysis: on that page, control-p is also overriden so you can not use it to open the print dialog at all. Additionally, there is a #media CSS for printer output that hides the content; all tested on Firefox).

I have implemented for disabling printing using window.onbeforeprint()
/*Block printing*/
window.onbeforeprint = (event) => {
console.log("onbeforeprint function");
printDiabled();
};
function printDiabled() {
var headstr = " <span style='font-size: large; font - weight: bold; color: Red''>PRINT IS DISABLED</span>";
//var oldstr = document.body.innerHTML;
document.body.innerHTML = headstr;
}
/*Block printing*/

if you have a scenario where u want to do something before print dialog appears or just after the document is sent to printer queue use can use the below events
window.onafterprint , window.onbeforeprint

For anyone coming here looking for an option using Bootstrap as I was, I used the following code to achieve this when a print button is clicked. This won't work when they press CTRL + P.
$("#print_page").click(function(){
$("#print_section").addClass('visible-print-block');
window.print();
$("#print_section").removeClass('visible-print-block');})
You need to add hidden-print to anything you don't want printed and then add an ID (or a class if you have more than one section) of print_section to the bit you want printed! Bit hacky but it works!

Related

Disable close and minimize option

Am a beginner to javascript, i have a doubt on this following :-
How to disable print popup window close button and minimize.Am working on a web application using java script.
As we all know print function will show a popup and it has a minimize and close button by default.
Is there any way to disable minimize and close button programmatically.
Is there exist any javascript method to do this?
myWindow.print();
Thanks,
Please help.
The 'print' window is created by your browser, not by Javascript (Javascript just says 'hi browser, could you print this for me?). Luckily, browsers do not allow the 'close' and 'minimize' button to be disabled, as this would create a VERY unfriendly user experience (just imagine sites that 'force' you to print a million pages for them). So, there's no 'how to' answer to your question, and that makes the world a better place.
I think print page help user to print it, so you take them to print page instead of minimizing it.. It will automatically go to print page..
function PrintWindow()
{
window.print();
CheckWindowState();
}
function CheckWindowState()
{
if(document.readyState=="complete")
{
window.close(); //you can edit it as you want
}
else
{
setTimeout("CheckWindowState()", 2000);
}
}
PrintWindow();

Custom Popup Displaying Before Closing Browser

I need a java-script or jquery code so that when every only I close my browser or
tab of the browser then my custom popup from will come out,
I don't want browser's default massage . I want to hide the default massages of the browsers
only my popup form will be displayed before closing.
And it need to be supported in three major browsers IE9,Firefox,Crome.
Again I am mentioning the default messages which comes from browsers which have two options 1.leave page 2.stay on page I want to hide them
Thanks in Advance,
No, that is not possible - and thats for a good reason!
Imagine, everyone could hide these messages from Browser, it would be a paradise for every criminal!
You can pop a dialogue on .unload(). Last I checked this was supported on IE/FF/Chrome/Safari but not Opera.
As for hiding the buttons to confirm that you want to leave the page or not, those can not be hidden or removed. As Haudegen said, for very good reason.
jQuery:
$(window).bind('beforeunload', function(){
return 'Dialog text here.';
});
JavaScript:
window.onbeforeunload = function(e) {
return 'Dialog text here.';
};

IE 9 and IE 10 cannot enter text into input text boxes from time to time

There is a web page with an iframe inside. Sometimes, Input text box controls, inside the iframe, are locked/ freezed. Users cannot enter text into them. But the text box can be focused and not faded. There is no code to disable the input controls and this does not always happen. Up until now, this is happening only in IE 9 and IE 10. Firefox and Chrome is OK.
Brief description of how the page works is:
There is a button on the parent page. By clicking it will build an
iframe from scratch and show it. This is done by Javascript.
Again, there is a button on the iframe to close it. By clicking it
will remove the iframe from the parent page's DOM.
Please let me know if you want further information as required. Thanks in advance.
This bug is very annoying, even worse there was very few informations we could find on google.
There is only one link from Microsoft that about IE9, but problem still exists in IE10 / IE11 and much easier to reproduce.
I have just create a fiddle to describe this problem
http://jsfiddle.net/WilliamLeung/T3JP9/1/
Why it is so hard for M$ to fix this issue for years?
there should be three workarounds
Reset the focus every time we modify the DOM with iframe
or schedule a "do nothing" time consuming task, which may make IE response to mouse event magically, I could not tell you why, maybe M$ could
The sample codes which setup a time consuming task
setInterval(function () {
var loopCount = 10000;
var x = 0;
for (var i = 0; i < loopCount; i++) {
x = (x + Math.random() * 1000) >>> 0;
}
return x;
}, 1000);
or reset the DOM content before remove it from document
someDivWithIframe.innerHTML = "";
$(someDivWithIframe).remove();
I am not sure if it helps for all cases, you should have a tried
The solution with jQuery worked on IE11 for me, not the other solutions.
$(theIframeElement).empty().remove();
An other solution working on IE9/10 was to set the iframe src to empty before deleting it
iframe.src=""
But this cause an exception "Access denied" on IE11 if you are using an older jQuery version < 1.11.1
Some links:
For information, jQuery also fixed this Issue for it's Dialog.js plugin that was displaying content in an iframe: http://bugs.jqueryui.com/ticket/9122
jQuery bug fix to IE11 "access denied" error: http://bugs.jquery.com/ticket/14535
I have managed to fix this bug by setting focus back to the main page. What I have done so far is:
put an HTML input textbox, which is set invisible, in the main page. When the iframe closes, I set focus back to that textbox.
Please refer following links for more information about this IE bug.
link1
link2
None of the solutions worked for me in IE 11.
Solved it by adding this code inside iframe:
$("input").first().focus().blur();
Obviously, this won't work if you don't have control over your iframe.
This worked for me on IE11,
Cause of issue (aside from IE being stupid):
Focused input element is removed from display inside a iframe (css display property)
Issue:
Text input element can not be clicked on, you can still tab to it however
Workaround:
We need to focus() a known visible element before taking a input field out of display, so on the line before we take the display away from a input field we have the line: document.body.focus();
Just to add to what others said, it is actually a problem when some input in an iframe is having focus which is then closed causing all other inputs to lose focus. And indeed having a script to set focus to an element solves the problem. But for me this wasn't working because some of my inputs were disabled. So the solution that worked for me is below
$("input[type=text]:not([disabled])").first().focus();
Complete snippet as I was using bootstrap modal and the modal had an iframe. I set the focus to an editable field before opening a model and after closing:
var modalInstance = $uibModal.open({
// modal properties
});
modalInstance.closed.then(function () {
$("input[type=text]:not([disabled])").first().focus();
});
modalInstance.opened.then(function () {
$("input[type=text]:not([disabled])").first().focus();
});
I originally wrote the plugin below to address memory leaks in IE 8, but consequently it also fixes this problem.
https://github.com/steelheaddigital/jquery.purgeFrame
Simple solution with Javascript which works for me and I saw no side effects in other browsers:
<script>
var pswElement = document.getElementById("password");
pswElement.addEventListener("focus", myFocusFunction, true);
function myFocusFunction() {
document.getElementById("password").select();
}
</script>
Anyway is quite sad MS is not able fix such problem in higher version too.
I was also suffering from this issue. As William Leung has pointed, IE has a bug with remove Iframe Object from DOM.
Try the following:
$(someDivWithIframe).empty().remove();
I had the same issue with IE11, angularjs and using an IFrame.
My template uses ng-switch to change view-modes.
One of the view-modes contains an IFrame.
The moment I switch away from the view-mode containing the IFrame:
var iFrame = <HTMLIFrameElement>document.getElementById("myIFrame");
iFrame.focus();
this.mode = ViewModes.ModeWithoutIFrame;
Solved the problem for me.
Here's the solution that worked for me, having tried all of the others on this page! Requires jQuery but I'm sure it could be rewritten in native JavaScript if that's necessary.
As with many of the other solutions, this should be added to the source of the iframe, assuming you have access to modify it:
$("body").focusout( function () {
window.focus();
});

Can I stop JS location.href without a popup?

I want to build a JS external script ( tag) which stops code (which usually isn't mine) like location.href from happening without the use of a popup.
I tried things like:
$(window).bind('beforeunload', function() {
window.stop();
event.stopImmediatePropagation();
event.preventDefault();
location.href = '#';
});
but nothing seemed to help.
again, I need it without the use of the: return "are you sure?"
maybe a different callback?
Thanks,
Dan
The right way to use onbeforeunload to confirm navigating away is to just return the string of the message you want to have shown. MDN has this to say.
The function should assign a string value to the returnValue property of the Event object and return the same string
So your onbeforeunload function for the behavior you ask for would just be (same as binding it with jquery, especially since onbeforeunload does not support multiple event listeners like other events do)
window.onbeforeunload = function() {
return "Are you sure?";
};
But ironically, Firefox doesn't support this for security purposes.
Note that in Firefox 4 and later the returned string is not displayed to the user. See bug 588292.
Edit: I read more of the bug report. The main reason they site for this decision is: "1. Remove the site-supplied text, since this is a security issue (untrusted text in browser dialogs)". I wonder how they feel about an alert?
Most modern browsers (Chome, IE 9+ or earlier, and Opera, I know for sure) will ignore anything you try to do in an onbeforeunload function other than returning a string for display. This is to prevent hijacking the users browser, opening popups, overriding navigation attempts by pointing the user another, possibly malicious domain, etc.
Edit 2: I was apparently incorrect. Only some things are disallowed in onbeforeunload, they just happen to mainly be the types of things you tried in your sample code, having to do with event propagation and page navigation. From deep in the comments of that FF bug report, user oyasumi posts a link to this jsFiddle with a work around for displaying custom text to FF 4+ users: http://jsfiddle.net/ecmanaut/hQ3AQ/ So apparently calling alert() is still allowed, even in onbeforeunload, which hilariously is doing exactly what the was original reason for the 'bug' "fix": displaying custom text in a browser/application/OS/official-looking dialog.
did you try to use "return false" ?
Also you should have the event sent to your function.
here is an example where you can prevent from a button click and hyper link
<input type="button" value="click me" />
google
$(document).ready(function(){
$('input[type="button"]').click(function(e){
e.preventDefault();
});
$('a').click(function(e){
e.preventDefault();
});
});
here is the link http://jsfiddle.net/juTtG/143/

The proper way to handle popup closing

I'm looking for close event for popup. I've found one for XUL, but I need it for HTML.
Popup has closed property.
>>> var popup = open('http://example.com/', 'popup', 'height=400,width=500');
>>> popup.closed
false
Well, I can check it once at half second.
function open_popup() {
var popup = open('http://example.com/', 'popup', 'height=450,width=450');
var timer = setInterval(function(){
if (popup.closed) {
alert('popup closed!');
clearInterval(timer);
}
}, 500);
}
I've tested it on Chrome 4.0.249.27, Opera 10.10, Safari 4.0.4, and Firefox 3.5.5. All works fine.
But setInterval bother me. It is ugly. Is there a better way of doing this?
UPDATE:
I use popups for authentication dialog (oAuth, actually). I wanna send some data to parent window after popup close (through postMessage).
Page inside popup from another domain. So, I can not add any event (unload) to it due security restrictions.
I can not use iframe due to iframe buster script. So, I can not use any fancy jQuery modal dialogs.
I can not edit anything inside popup.
You might want to look into the unload event, take a look at Javascript: Popups
edit: as you've said you cannot edit anything inside the popup, there really aren't any options left. I believe your current setInterval code does the job just fine. You should ask yourself if realtime detection of the popup closing is absolutely critical. That 500 milliseconds timer certainly won't strain hardly any resources or bring someones computer to its knees.
I have used jQuery Dialog and it has a close event
http://jqueryui.com/demos/dialog/.
Am not sure if I understand your question right,why do you want to use the timer ?
Use window.opener in the pop-up window. i.e. something like:
onunload = opener.alert('popup closed');
or
onunload = opener.nameOfAFunction();

Categories

Resources