views:

209

answers:

2

Background:

I'm writing a script (in VBA, if that matters) to input data into a web-based system. Some of the system's validation is only run when a field is focused, so I've been calling .Focus on the fields in VBA to force it to run. But that steals the systemwide focus; rather annoying if I am doing anything else while the job is running.

I want the validation to be triggered without stealing the focus. So I am trying to directly call whatever event handler is registered to the input field.

Problem:

All event handlers in the web app are added with element.attachEvent(), which means the onfocus and onblur properties (which I believe are the ones I want) are not set.
Is there any way to retrieve the handlers without resorting to even more evil hacks?

Alternatively, is there a better way to do this without having to find the event handlers? I'm pretty new to JavaScript, so I could easily be missing something.


Edit: Is there any other reason the focus might be stolen by the VBA code? I cannot find any other references to .Focus or even AutoIt's WinActivate, but even with the suggestions here, the problem still occurs.

A: 

The whole VBA part aside, you appear to have a reference to an element, so you can try calling element.focus() or element.blur() to trigger the focus and blur events respectively.

Roatin Marth
But `.focus` seems to grab the systemwide focus anyway, which is what I'm trying to avoid.
Michael Myers
Not with a lowercase `f`.
Roatin Marth
I'm just saying that I tried it and it did. Unless I was doing something else that caused it, but I didn't see any other calls to the uppercase `Focus`.
Michael Myers
@mmyers: hmm interesting. Perhaps I'm not familiar enough with the VBA part of this question. If I call `setTimeout(function(){ $('[name=q]')[0].focus() }, 2000)` on this page, then switch to a different application (eg Powerpoint) and wait 2 seconds, the page does *not* steal focus again.
Roatin Marth
I'm not familiar with VBA either, but I searched again and I still can't find anything that would steal focus. I hope this question isn't completely unrelated to the real problem.
Michael Myers
A: 

Take a look at this post.

This function should fire the event for you:

function fireEvent(element,event){
    if (document.createEventObject){
        // dispatch for IE
        var evt = document.createEventObject();
        return element.fireEvent('on'+event,evt)
    }
    else{
        // dispatch for firefox + others
        var evt = document.createEvent("HTMLEvents");
        evt.initEvent(event, true, true ); // event type,bubbling,cancelable
        return !element.dispatchEvent(evt);
    }
}

Do you have access to the application you are interacting with (to be able to add this function)?

pkaeding
No, but I may be able to do that from VBA. I'll give it a shot now. Thanks!
Michael Myers
Also, this is an internal application which is guaranteed to use IE, so that makes it easier.
Michael Myers