What event is fired when window.print() is called? - javascript

I am trying to work through this question and I have had little success tonight. I think I can make the code below work if I only knew what event was fired when the window.print() function is called.
var browser_name = navigator.appName;
if(browser_name == 'Microsoft Internet Explorer'){
window.attachEvent("print()",on_print_function);//I realize I cannot attach an event listener to a function, I just wanted you to see what I am trying to accomplish
}
else{
window.addEventListener("print()",on_print_function,false);
}
The function that is called when the print event takes place returns a page that stores some info in the database.
My end objective is to have the page print ONLY if the info in question is going to be stored in the database. I am open to better ways of tackling this, but I think I will have it going ok if I can just get the event for the print() as I said.
EDIT
I am giving up on this for now, I have settled with another way of doing what I want. I look forward to the day when FireFox supports onbeforeprint() and onafterprint().

Well as far as I know, IE has several events line onbeforeprint() and onafterprint() but they are not supported by other browsers. So relying on this is not very good.
Perhaps you can have a print button on your page. Attach to it a handler which executes the ajax call to the server to store the data to the database and on success of this call, call the print() on the window.
Is that what you are looking for ?

Apparently you can now listen for this with Firefox (but not other browsers):
Some browsers (including Firefox 6 and later and Internet Explorer) send beforeprint and afterprint events to let content determine when printing may have occurred. You can use this to adjust the user interface presented during printing (such as by displaying or hiding user interface elements during the print process).
The afterprint event is raised after the user prints or aborts a print dialog.
https://developer.mozilla.org/en-US/docs/Web/API/window.onafterprint
You may be able to emulate this with media queries in other browsers: https://stackoverflow.com/a/18325463/421243

Related

Why does 'stay on page' dialog pauses asynchronous function?

So this is really bugging me, I don't know if it is a browser related glitch or javascript just works that way ( I hope it does). I created a fiddle. https://jsbin.com/laluziqede/1/edit?html,js,output
Open your console, then click the button. When the dialog appears the function continues normally (first console.log isn't paused), however the one inside setTimeout function is paused and will only show after you click 'stay on page'.
But why, could someone explain this? I want to use this property in my application (execute an action right after user clicks stay), but I'm not sure if it's a good practice and is it working on all browsers and devices.
Edit: Here's the code from the bin:
$(window).on('beforeunload', function() {
return 'Check your console please and then click stay';
});
$('#click-me').on('click', function() {
window.location.href='about:blank';
console.log ('dialog won\'t stop me from showing');
var timer=setTimeout(function() {
console.log('this was paused by the dialog');
},0);
});
The behaviour is browser dependent. I tested it in Firefox, Chrome, IE and Edge, and of those only Chrome has the behaviour that you describe.
The difference lies either in when the beforeunload event is triggered, or when it is handled. Most browsers trigger the event immediately when you change the location property and also handle it immediately. Chrome either triggers and handles the event when the navigation is actually about to happen, or places the event on the queue and handles it later just like regular events.
In Chrome the code inside the setTimeout handler will not happen until after the beforeunload event is handled, either because the navigation is handled before any queued events, or because the timout event is after the unload event in the queue.
Javascript is single threaded (unless you start using things like WebWorkers and other newer technologies). So the timer function schedules something to be done, but it will only be done when everything else has yielded control of the javascript thread. So timer is only asynchronous in the sense that you're asking for some work to be done after some period of time, but it is not truely asynchronous in the sense that that something can be done while something else is also being done.
This applies to things like XHR requests as well, even though the XHR request are indeed dispatched asynchronously, the responses are all handled synchronously one at a time.
Your specific example is a bit odd in that it's not another javascript function that is blocking, it's a browser security feature that is making sure you want to let the previous javascript operation take you away from the current page. The concept is the same though.

Using setTimeout in javascript to simulate php's sleep

I have an AJAX function which takes some time to complete. When it's done I want to open a new tab with the result. To do so I've came up with three options:
Use window.open() from the AJAX-call
Use window.open() in the javascript function/event trigger.
Use window.open() in a setTimeout-function within the javascript
function/event trigger.
The problem is this has to work with all major browsers (IE, Chrome, Firefox and Safari) and option 3 should do the trick but is has unwanted side effects:
In Chrome the window is not opened in a new tab but as a pop up.
In Safari the internal popup prevention is activated; resulting in
not opening the popup. (source)
Now I figured to use setTimeout() as a piece of procedural code and ending up with some like:
$('.selector').click(function() {
doAjaxCall();
setTimeout(function(){ }, 150);
window.open(...);
});
Well, this works for Safari but Chrome and FireFox seem to ignore the setTimeout() and continue directly to the window.open(). Herein lies my problem; the data that has to be used isn't always up to date when window.open() gets called.
So, here I am. Back to basics. Figured out what the symptoms are, knowing the downsides of my explored scenario's and ended up with a something like this:
$('.selector').click(function() {
doAjaxCall();
for(i = 0; i <= 100000000; i++) {
// procedural and time consuming so doAjaxCall has enough time to complete
}
window.open(...);
});
In my case I'm stuck to xajax for the ajax-handling, so I can't use jQuery's ajax solution.
Any suggestions on how to improve this? Resulting in a solution where all major browsers open the popup when the ajax-function has completed?
First of all, the browsers don't ignore the setTimeout function, but the execution doesn't stop and wait for a setTimeout completion, but will continue it's execution and wait for the timeout to complete in order to execute the method passed as argument to setTimeout method.
But you don't need to simulate the sleep method from php in order to achieve what you want.
The ajax call has a success event which you can attach an event handler on. Open your new tab when the success event occurs. Otherwise, you wont be able to know exactly when the ajax request ended. If you can't use the jQUery's ajax, you can create an 'old-school' ajax request, like here
Also, opening a new window is not the best solution, because most browsers have popup blockers.

IE9 firing onbeforeunload event when the window opens

I'm building a site using the JFileUpload applet and want to handle the closing of a page in a certain way. JSTransferCancelled is called when the applet is cancelled. The following code is what I'm using to handle these events and it works in all browsers except IE.
function JSTransferCancelled(){
bCancel=false;
$.post("cancel.php");
self.close();
}
$(window).load(function(){
$(window).bind('beforeunload',function(){
document.uploader.setEnabled(false);
if(bCancel){ document.uploader.cancel();}
});
});
I open the page with the uploader on it in a new tab from the main site and want to close it when they cancel the upload. When I open the tab in IE, however, I instantly get the alert saying The webpage you are viewing is trying to close this tab. Do you want to close this tab? [OK] [Cancel] and my uploader is both inaccessible because of the setEnabled(false) call and cancelled because of the cancel() call.
What I'm looking for is the same functionality, just in IE. I know there are many many many issues in IE with events like onbeforeunload with it triggering in response to different things, but I've checked for all of those problems in my site and haven't found anything. I haven't run into anything online that deals with the kind of problem I'm having.
I've tried wrapping the onbeforeunload function in different things such as the load function above as well as $(document).ready(), but they either give me the same problems or create new ones.
Check Microsoft's Ridiculous Documentation Then make sure none of the code you are using does anything they list as a trigger to invoke beforeunload, which includes several things that do not actually unload the page (go Microsoft!)

debugging into a javascript anonymous function

I am trying to reverse engineer a Microsoft CRM 2011 web page. The page loads a massive number of scripts and HTML. My current development focus is on the click event of a checkbox element on the page. Clicking the element causes behavior on the page to change, and I want to walk through the code that handles this.
The problem is the checkbox's click handler is attached during page load via an anonymous method. So the code is there, but trying to find it is asking one to locate a needle in a haystack.
Is there a technique using the Internet Explorer debugging tools to somehow make the debugger stop when the checkbox is clicked? There may not be, but I thought I would ask.
Your best bet is to run this in the console:
document.getElementById('theCheckBoxId').onclick
If null appears in the console, you can continue reading. Otherwise the onclick handler and it's code should appear right there in the console.
Use Chrome's dev tools: Right click something on the page -> inspect element. You'll see this:
Go to "SOURCES" (no longer called "Scripts") and there is a '||' Pause button as you see in the screenshot. If the page doesn't fail, you can check the checkbox, and since scripts are paused, you'll see the code for the anonymous function become highlighted and the page will be frozen. You can then use the tools to step through the code.
However, we can certainly better help you with what you actually want from the page...
You can also use attach a onbeforescriptexecute from the console: https://developer.mozilla.org/en/DOM/element.onbeforescriptexecute
You would be something like this in the console:
document.getElementById('theCheckBoxId').onbeforescriptexecute = function (e) {
alert('hey same thing as pausing the script!');
console.error('script with this id about to run: ' + e.target.id);
//Could also try .src .innerText etc.
//Reference this: https://developer.mozilla.org/en/DOM/element.onbeforescriptexecute
//the full argument to checkout in the console:
console.error(e);
};
You can also play around with the currentScript method: https://developer.mozilla.org/en/DOM/document.currentScript
You can also right click and inspect the check box, and then on the right panel of dev tools, look at the 'Click' event listener code, but often this is garbled and hard to work with.
It sounds like you have no way of modifying the anonymous function that is tied to the checkbox click event. If not, perhaps you can create a second event handler, but define it before the definition of the existing event handler.
Event handlers in the browser typically fire in the order they were defined. See http://jsfiddle.net/aroder/kkYfX/2/. If you defined your own event handler, it will give you a place to attach the debugger at least somewhere close to the anonymous function you are trying to step through.
Also, use the debugger statement to automatically break your code. If you are using IE, ensure the options under Tools > Options > Advanced > Disable Script Debugging (Internet Explorer) is UNchecked.
<script>
// the debugger statement will automatically break in IE dev tools, Firebug, and Chrome dev tools
debugger;
</script>
Older version of IE is pretty lame specially when it comes to debugging AJAX applications. Firebug is the best that I have seen. It lets you replace an existing javascript function with your own. This is what I suggest.
Open the web application in Firefox
Copy sourcecode of existing function
Format it and add the following statement to the function at the place where you want it to stop and inspect the variables.
debugger;
Paste the new code in Firebug's console window and click on Run .. that's it!

Get URL of a webpage dynamically with Javascript on a Firefox extension

I'd like to get the URL of a webpage dynamically (i.e if the url changes get the new url) using Javascript with a Firefox extension.
So far I've tried to use an event listener attached to the current window but it doesn't work.
( Display Webpage current URL with Firefox extension )
Can someone post some code to show me a way to achieve this please ?
You could add an event listener to the URL bar (I explained in a comment why the code in the answer to your old question didn't work) but frankly - this isn't the best way. URL bar contents can also change if the user starts typing into it for example. And the user could even choose to remove the URL bar from the browser window.
The best way to achieve this is implementing a progress listener. You can find example code and explanation on https://developer.mozilla.org/en/Code_snippets/Progress_Listeners. You would be interested in calls to the onLocationChange method, that will happen every time the URL bar contents need to change (also when the user switches between tabs).
You could try listening to the hashchange event on window object. Both chrome and firefox support it. Not sure about IE though.
window.onhashchange = function () {
hashChanged(window.location.hash);
}
If your browser doesn't support "hashchange" event, you could use this plugin http://benalman.com/projects/jquery-hashchange-plugin/ .

Categories