The CRM Grid – A Microsoft CRM Blog

Greg Owens’ rose-tinted MS-CRM mumblings

Archive for June, 2009

Event execution order with ‘onbeforeunload’

Recommended JavaScript Book!

I'd also like to highly recommend this JavaScript book by Douglas Crockford - it will definitely improve the quality of your JavaScript development experience!

Recently I had a requirement to conditionally add some dynamic script to the onClose event for a CRM form. Given the flexiblility demanded by the requirements, it was not practical to write script in the form’s onClose() event hander in the CRM Form Properties window. Instead, I used Internet Explorer’s attachEvent method

The problem with the attachEvent method is that the collection of functions that are appended to the event are executed in “random order”. “Random” is rarely a desirable sequence  in my experience and in this case one cannot guarantee that a custom dynamic “validation check” (for example) will be executed before the default event handler (i.e. the one that may ask “Are you sure you want to navigate away from this page?”).

Alas a simple solution is at hand, thanks to this post made by “Adios” over at The function below will effectively inject your function call before the default event handler.  Obviously this function can be easily amended to deal with any type of event but the example  below is hard-coded to deal with the “onbeforeunload” event handler.

Define this function in your form onLoad script (or somewhere in your global code, if you have adopted a custom solution for centralising your JavaScripts):

function addbeforeunloadEvent(func)
    var oldonbeforeunload = window.onbeforeunload;
    if (typeof window.onbeforeunload != 'function') {
        window.onbeforeunload = func;
    } else {
        window.onbeforeunload = function() {

Then use the following snippet to insert your function ahead of the default or existing event handler:

//TODO: replace myFunctionName and myParameter list to match your custom function signature