1

I have a Greasemonkey script that automates inputting user info. But before the form can be submitted, the fields have to be in focus (I think they use AngularJS to verify that a valid name/email has been entered). So in my code I do:

document.getElementById('name').value = "Name here"; //Enter name in field
document.getElementById('name').focus(); //Focus on the field

This works fine but only when the window is active. If the window is not active, it will enter the name but the field will not come to focus (so it cannot be submitted). Is there any modification that can be done to fix this?

Edit: It is hard for me to provide an example because the code has to be run from a window that is not active but here is the code for the input field.

<input id="namefield[name]" name="name" ng-model="nameField.form.name" ng-pattern="nameRegex()" placeholder="John Doe" required="" style="width: 246px" type="text" class="ng-valid-pattern ng-dirty ng-valid ng-valid-required">
Brock Adams
  • 90,639
  • 22
  • 233
  • 295
Bijan
  • 7,737
  • 18
  • 89
  • 149
  • This question is still incomplete; we do not have enough info to replicate the problem. If the answer below does not work, then the page is dynamically altering focus (or the target node(s)) and you really must either provide access to the offending page or pare it down to a concise, publicly-posted example that exhibits the same behavior. – Brock Adams Jan 13 '15 at 09:33

1 Answers1

1

AngularJS is heavily AJAX driven, so it is probably a timing thing. JS, especially timers, is slowed down on pages that don't have focus.

So, it may be that just using AJAX-aware techniques will be enough. EG:

// ==UserScript==
// @name     _Focus the name input
// @include  http://YOUR_SERVER.COM/YOUR_PATH/*
// @require  http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// @require  https://gist.github.com/raw/2625891/waitForKeyElements.js
// @grant    GM_addStyle
// ==/UserScript==
/*- The @grant directive is needed to work around a design change
    introduced in GM 1.0.   It restores the sandbox.
*/
waitForKeyElements ("#name", focusInput, true);

function focusInput (jNode) {
    jNode[0].focus ();
}

Note that the question code lists: <input id="namefield[name]"... but searches for id name.
If this isn't an error, it is a sign that AngularJS is rewriting the HTML (I've not yet learned much AngularJS) -- which would be further evidence that that the original script worked at all was due to winning a race condition. That is, not reliable at all.

Community
  • 1
  • 1
Brock Adams
  • 90,639
  • 22
  • 233
  • 295