John Armstrong
ServiceNow Employee

One of the important differences to note about scripting in the Mobile UI is that synchronous javascript or glideRecord calls are not allowed.   In practice, it's pretty easy to script around, and the product documentation provides examples why this is done, and how it works.

 

All Javascript run on a browser shares a single thread, meaning everything that executes has to wait in line.   If something in a script takes a second or two to complete, your browser needs to wait.   If this goes on long enough, it may seem like your browser is hung.

 

The way to get around this is to make an Asynchronous call.   This allows us to move requests we've made to another thread.   Your browser has a pool of threads it uses specifically for asynchronous calls like this.   Meanwhile, your browser can move on to it's next task.   When the request is finished, a callback function is triggered to handle the results of the request.   Here's an example of the mobile platform not allowing synchronous JavaScript calls. The g_form.getReference() method must now have the callback parameter defined.

 

 

var userName = g_form.getReference('assigned_to').user_name;
g_form.setValue('u_assigned_user_name', userName);

 

 

Above, we're making a g_form.getReference   call to get the a user name based on the contents of the assigned_to field.   Once that's done, we're setting the u_assigned_user_name field to that value.   The problem with this is that we're waiting for that getReference call to process.   This might only be a fraction of a second, but it might go a bit longer. But, you might have more that one of these in your script, and several scripts that execute on your form.     This can add up!

 

Here's the asynchronous version:

 

 

g_form.getReference('assigned_to', function(gr) {
        g_form.setValue('u_assigned_user_name', gr.user_name);
});

 

 

Here, we've added a second argument to getReference.   This second argument is an anonymous function, and has an argument called gr, which stores the results of our getReference call.   Within that function, a setValue call assigns a value to u_assigned_user_name, just like the second line of our first example.   This function will execute whenever the getReference call finishes.   Since this is now in another thread, the browser can move on to other things.

 

 

Further Reading

Mobile Client GlideForm (g_form) Scripting

Client Script Best Practices

Mobile GlideForm (g_form) API Reference