Cancel button was tapped when nothing is done - javascript

I did read those three posts:
Handling Alert with UIAutomation
UIAutomation : Cancel button on Alert view is tapped without actually doing it
UIATarget.onAlert = function onAlert(alert) Issue - Script doesn't seem to go into block correctly
and I know this issue can be fixed. I tried to use the methods which people came up with in the posts but it doesnt really work for me. I would like to ask here again...
So I need to type a password on the alert window. Like this:
target.frontMostApp().keyboard().typeString("1234");
I was wondering if I should write the onAlert function first, and put this line of code after the onAlert function? Or write the onAlert function first, and then put this line of code inside the onAlert function?
I tried to do something like this:
UIATarget.onAlert = function onAlert(alert)
{
return true;
target.frontMostApp().keyboard().typeString("1234");
}
But it is not working... The cancel button is still being tapped... Thanks!

I see two problems. First, the typeString line will never be executed because it comes after the return line in the function.
function myExampleFunc() {
{
doSomething(); // executes
return true; // exits from the function
doAnything(); // never executed. ever.
}
The second thing is that it looks like you're trying to catch an alert that's generated by your own application:
target.frontMostApp().keyboard().typeString("1234");
You don't use onAlert to catch these; onAlert is for handling iOS alerts like permissions popups.

Related

How can I stop execution of javascript function until user action?

So im trying to replicate the window.confirm() prompt in javascript. here is the structure of what i tried.
function foo(){
if(customConfirm("Click yes or no"))
alert("Clicked yes");
else
alert("Clicked no");
}
function customConfirm(message){
$('#customConfirm').load("customAlert.html");
$('#okButton').click(function(e){
ret = true;
})
$('#cancelButton').click(function(e){
ret = false;
})
return ret;
}
If you're using raw JS, or at most JQuery instead of say React, Vue, etc., I would provide callbacks for the "customConfirm" so that say when you detect a button press on Ok and Cancel, and call each callback accordingly. This would require the use of event handlers which is fairly basic with raw JS, and even more so with JQuery...
Here's a basic idea of what I'm saying (forgive me if the code is incorrect, I haven't used JQuery let alone frontend JS in some time now.
function displayConfirm() {
// Let's pretend the confirm "modal" has two buttons, one with id "okButton" and the other with "cancelButton". We shall use this later.
}
function updatePage(cancelled) {
// Here is where we would update the page depending on whether or not the confirm was cancelled.
}
$('#okButton').click(function() { // We don't use e, so we're just gonna ignore it... I think you can anyways, if JQuery throws a fit, use _ instead of e for the variable name as it just tells JS "hey, this variable, we don't use it."
updatePage(false);
}); // Consistently use semicolons, look into ESLint if you're forgetful like me lol
$('#cancelButton').click(function() {
updatePage(true);
});
It's as simple as that. Since JS doesn't allow you to just pause execution like that (well you can, but it just freezes everything else, such as when you don't ever break from an infinite loop, or recurse with no exit condition (unless JS does a Python and has a recursion limit)), we use just a callback for when that event is received. So unfortnately afaik you can't really wrap this into a function... Aside of maybe using promises? I don't think you can but it may be worth some research if you really, for whatever reason insist on using a function to wrap it all.

Understanding the return this in timer.js

I was just going through the code of timer.js, playing around with the dev tools in Chrome, and basically I call the plugin like so:
var timer = $.timer(function(){
$('#add-html').html('Hello There !!');
});
timer.set({ time:5000 , autostart :true });
Even the demo uses the same example, now when the below line executed:
var timer = $.timer(function(){
$('#add-html').html('Hello There !!');
});
This line inside the plugin executes and returns this, but what is return this at this point? Is it an instance of the whole plugin? Or what is it exactly, I know without it an error is thrown, but what exactly is return this used here for and what is its value?
I use return this a lot for chaining etc in JavaScript, but somehow I am not able to understand the contextual usage of the return this here. Would anybody explain ?
You should just run this in a debugger (set either a breakpoint or a debugger statement) and evaluate this at that point.
For me, this === jQuery is true on the first run and this instanceof $.timer is true on subsequent runs.

First ajax call in $.deferred() chain never gets there, but second click on button works fine

I am using jQuery to set up a chain of function calls, two of which are ajax calls to ASP.NET MVC actions (in the same controller). Frequently, on the first try, the first AJAX call never gets run and the process hangs. The breakpoint in the Action never gets hit, and the loading dialog shows it's pretty face forever.
A different code path that doesn't have the same function (thisActionCanHangAjax) doesn't seem to have issues, but I am not 100% on that.
I can cancel the process (refresh the page, timeout, dismiss dialog). The second time I click on the button it will go through with no problem, and nice and quick as expected.
I am newish to using jQuery with deferreds/promises, so I am hoping there is something stupid I am doing wrong here (or in the controller, but that doesn't seem likely).
The jQuery chain and javascript looks like this:
// <input type="button" onclick="fancySubmit()">Go Speed Racer Go</input>
function fancySubmit() {
jQuery.when()
.then(openLoadingBox)
.then(thisActionCanHangAjax) // this one sometimes hangs/etc. call doesn't reach MVC
.then(getAdditionalDataAjax)
.then(submitSimpleForm)
.done(closeLoading) // modal('hide')
.fail(showLoadingError);
}
function thisActionCanHangAjax() {
// POSSIBLE ISSUES HERE? this action returns JSON on success, but we don't care.
// any errors raise a 500 with custom message
return $.post('#Url.Action("ThisActionCanHangAjax")', $("#basicForm").serialize());
}
function getAdditionalDataAjax() {
return $.getJSON('#Url.Action("GetAdditionalDataAjax")');
}
function submitSimpleForm(jsonDataFrom_getAdditionalDataAjax) {
// create form and append to body, post form, delete <form> element
return true;
}
function openLoadingBox() {
// MAYBE THE ISSUE IS HOW I AM DOING THIS ?
var dfd = new jQuery.Deferred(function () { $("#loading-dialog").modal('show'); });
$("#loading-dialog").on('shown', function () { dfd.resolve(); });
return dfd.promise();
}
The ASP.NET MVC Pieces are quite simple, tested code. Signatures look like this:
[HttpPost] public ActionResult ThisActionCanHangAjax(TheModel model)
{
try { return new JsonNetResult(new { ok = true }); }
catch (Exception e) { return new HttpStatusCodeResult(500, e.Message); }
}
[HttpGet] public ActionResult GetAdditionalDataAjax() {
// just reads a bunch of basically static stuff, and returns it.
return new JsonNetResult(new {name="Paula", level="Brillant" });
}
For what it is worth, there is no way for us to debug server side in production, and dev isn't a perfect reproduction (e.g., we don't have a giant IBM mainframe backing this there) Because of the fact that the action executes fine/fast/is well tested, I don't consider that an issue. We are simply using the same function as always, but from AJAX and not as part of another action.
I think you want :
jQuery.when(openLoadingBox)
.then(thisActionCanHangAjax) // this one sometimes hangs/etc. call doesn't reach MVC
.then(getAdditionalDataAjax)
.then(submitSimpleForm)
.done(closeLoading) // modal('hide')
.fail(showLoadingError);
you can't just leave the .when() empty like that
of course that commented line never happens and hang, you are saying when nothing is finished , then do this.... so , it never happens

function not working correctly unless there is an alert

The problem
I am having is the following code will not update the tow select boxes "select1" and "select2", unless I have an alert immediately preceding the code.
Background info -
I am posting two variables to this page, "sel1val" and "sel2val", and I am assigning them to hidden input boxes with id's "sel1valtry" and "sel2valtry" respectively. I am assigning the values of these input boxes to the variables in the function and have named them "sel1val" and "sel2val". I can post more code if need be, but it is what I call "franken code"...haha! because I am a novice, it is assembled from many different styles of code.
Objective - what I am trying to achieve is to set two select boxes based upon the value of "sel1val" and "sel2val". The correct functionality is only obtained when I have an alert prior to the code.
Methods I have tried - I have left in some commented out code, to illustrate my attempts. I have been through many forums and that is where I got these ideas from. I suspect that the alert "reloads" the javascript part of the page, but I have no real basis for this. I have tried "document ready", variations of "window load", and even tried slowing things down with a delay, in case it was a timing issue. Each of the methods I have tried have resulted in the same outcome, whereby it only works with an alert.
I have achieved much success with my web based projects, and this would not have been possible without the invaluable resource in forums such as this one. I would like to thank anyone that has ever provided input/solutions, as without this I would never have been able to progress.
$(document).ready(function(){
// $(document).ajaxSuccess(function(){
// alert("AJAX request successfully completed");
// });
//$(window).load(function()
//window.onload = function()
//$(function ()
//Code goes here
//alert("got here");
//{
var sel1val = $("#sel1valtry").val()
var sel2val = $("#sel2valtry").val()
if (sel2val)
{
//alert("will not work without this alert"+sel1val);
//$("#select1").delay(2000).val(sel1val);
//$("#select1").val(sel1val);
$("#select1").prop('value',sel1val);
// var element = document.getElementById('select1');
// element.value = sel1val;
dochange('selection2', sel1val)
//var element = document.getElementById('select2');
// element.value = sel2val;
alert("will not work without this alert"+sel2val);
$("#select2").val(sel2val);
}
//}
});
//}
It seems like the dochange function is using some asynchronous API (like an AJAX call for example) which is setting value to the sel2val variable in its success callback. But since AJAX is asynchronous, this function returns immediately, not waiting for the server to return a response. By putting an alert you are blocking the execution of the next line of code and leaving enough time for the AJAX call to complete and assign a value to the sel2val variable.
The proper way to fix your code is to provide a callback to this function where you will perform the necessary actions:
dochange('selection2', sel1val, function(result) {
$("#select2").val(result);
});
And in your dochange function you will invoke this callback in the success event of your AJAX call.

Javascript: how to make changes to the document before function finishes running?

I want to create a function that when called would display a "Loading..." message, and display the results as soon as it finishes. when I do it like this:
function load() {
$('#status').html("loading...");
/* do something */
...
$('#status').html("done");
$('results').html(result);
}
The "loading" message never appears, after a while what a user sees is just the "done" message and the results. How can I make the "loading" text appear just the moment I want it to?
If "do something" is synchronous, the browser never gets a chance to update the UI between the two content changes.
To have the changes appear you need to do something like:
$('#status').html('loading...');
setTimeout(function() {
// do something
$('#status').html('done');
}, 0);
The setTimeout call gives the UI a chance to update the display before jumping into your "something".
Note that if possible you should try to ensure that "something" doesn't tie up your browser for a long time. Try to break the task up into multiple chunks, where each chunk is also dispatched using setTimeout().
Hard to tell without seeing the "stuff" part, but I hope this helps a little;
function load() {
$('#status').html("loading...");
function onLoaded(result) {
$('#status').html("done");
$('results').html(result);
}
// do your stuff here
// Not being able to see the "stuff", I guess you do some AJAX or something
// else which is asynchronous? if you do, at the end of your callback, add
// onLoaded(result)
}
The key is in the "do something". It depends on what you want to do but I would expect that you want to use jQuery's load() function.
Many jQuery functions accept 'callback functions' which are executed after the task is complete. The callback function section of the load() documentation should explain everything.

Categories