You cannot do this in the onBeforeUnload. The for this reason is; the user has already sent in a request to move away from the page and the event has been intercepted. The confirm is the best you can do, unless you prevent the event further up the event chain (such as with onkeydown).
For instance, if you want the user to not be able to use their keyboard to go backwards and forwards in history, or to reload the page, this could be achieved using;
var catchKey = { 37: true, /// left 39: true /// right }; window.onkeydown = function(event) { if (catchKey[event.keyCode] && event.ctrlKey) { event.preventDefault(); event.stopPropagation(); } }
Hope that helps!