简体   繁体   中英

Text field won't focus unless window is in focus

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">

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM