1

I'm trying to simulate onclick event in a h:commandButton when I close my browser.

Here is my code:

<body onBeforeUnload='closingBrowser()'>


function closingBrowser() {
    document.getElementById('main:commandButtonHidden').onclick();
    return false;
}

This javascript function call the function associated with my button which has this definition:

<h:commandButton id="commandButtonHidden"
   value="checkPasswords().Login" 
   onclick="javascript:checkPasswords();" actionListener="#{init.closingBrowser}" />

and checkPasswords():

function checkPasswords() {
  alert("checkPasswords");
  return true;
}

This function has nothing interesting because what I want is the function in my actionListener.

This works perfect in IE and FF, but not in chrome or Opera.

The alert always is fired in all browsers, but the actionListener NO, just in IE and FF, and it has no sense.

Somebody knows anything about this.

Thanks

David
  • 11
  • 1
  • 3
  • what is h:commandButton? – David Murdoch Oct 12 '10 at 19:55
  • Could you be more explicit?? Is there something wrong. That code works ok in IE and FF, the actionListener is not fired in chrome and Opera, however if I click directly over the button works perfect in 4 browsers. Thanks. –  Oct 15 '10 at 18:13

3 Answers3

2

In case anyone bumps into this looking for a framework agnostic way to fire any HTML and Mouse event, have a look here: How to simulate a mouse click using JavaScript?

Community
  • 1
  • 1
TweeZz
  • 4,779
  • 5
  • 39
  • 53
0

Wild guessing: try firing a click event, instead of accessing the onclick callback.

document.getElementById('main:commandButtonHidden').click();
Matchu
  • 83,922
  • 18
  • 153
  • 160
0

I found this while searching for the solution to this problem. I'm hoping its not too late for you but I did:

(with jQuery)

var element = jQuery("#" + elementid);
if (element.length > 0 && element[0].click == null)
{
    element[0].click = function ()
    {
        var mouseEvent = document.createEvent("MouseEvent");
        mouseEvent.initMouseEvent("click", true, true, window, 0,
        element.offset().left + window.screenX, element.offset().top + window.screenY,
        element.offset().left, element.offset().top, false, false, false, 0, null);
        element[0].dispatchEvent(mouseEvent);
    };
}

if you don't want to use jQuery (and you don't need client/screen x/y co-ords)

simply try:

var mouseEvent = document.createEvent("MouseEvent");
mouseEvent.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, 0, null);
var element = document.getElementById('main:commandButtonHidden');
element.dispatchEvent(mouseEvent);

from: https://developer.mozilla.org/en/DOM/document.createEvent

James Khoury
  • 21,330
  • 4
  • 34
  • 65