User Tools

Site Tools


j

Welcome to our SNOW INFO PAGE Section J


JavaScript

- See Also

Separate Document: JavaScript_2020

JavaScript Log and Field Watcher Pane https://docs.servicenow.com/bundle/paris-application-development/page/script/debugging/concept/c_FieldWatcher.html - “JavaScript Log” and “Field Watcher” are two separate tabs on a special debugging pane which may be turned on for client-side debugging purposes. - JavaScript Log - The JavaScript Log is available directly from your web browser via F12. In chrome, it is labeled “Console”. The JavaScript Log is also available via a special pane which may be displayed at the bottom of a form via the Gear icon at the top right of any form (Settings / System Settings - Developer - “JavaScript Log and Field Watcher”). Unfortunately, this setting seems to always turn itself back Off, every time you load a form with the Browser's refresh button or F5. So, you may instead need to use the special Additional Actions (hamburger menu) - Reload Form command. This method should keep the pane visible after the form reloads. - Field Watcher - The field watcher tool tracks and displays all actions that the system performs on a selected form field. - Can be used to track actions taken on the field by all of the following types of objects from both the Client side and Server side: Client Side: Client Scripts, UI Policies, UI Actions Server Side: Access Controls, Business Rules, Data Policies. - Can NOT be used to debug Script Includes. That is, the Field Watcher will Not show which script includes were invoked by the other objects. - Only one field can be watched at a time. - Non-admin users with the impersonator role do have access to the field watcher feature. - The field watcher tool tracks and displays all actions that the system performs on a selected form field. - Can be used to track actions taken on the field by all of the following types of objects: Access Controls, Business Rule, Data Policy, UI Policy, Client Script, UI Actions. Perhaps can NOT be used to debug Script Includes. - Only one field can be watched at a time. - Non-admin users with the impersonator role have access to the field watcher feature.

JavaScript – Miscellaneous

- JavaScript IS an object-oriented programming language. - JavaScript is NOT a strongly typed language. (It is “untyped”.) You do not need to specify the data type of a variable when declaring it. - A semicolon denotes the end of a code statement, but you do not need a semi-colon at the end of a line. - JavaScript IS case-sensitive. - JavaScript is the language of the web because of its Asynchronous capabilities. - The only distinction between client-side and server-side JavaScript is the set of library objects which are available to you. - Escape Characters \n \' \“ - Like other languages, parentheses ( ) may be used to change the order of arithmetic operations.

JavaScript - Scope Considerations

- Scope is the concept, in programming, that some variables are accessible (or inaccessible) from other parts of the program. - Scope is the context in which variables are declared. - Variables can exist either outside or within blocks { }. - In global scope, variables are declared outside of blocks. They can be accessed by any code in the program, including code in blocks. - It is a best practice to Not declare variables in the global scope. - If a variable does not need to exist outside a block, it shouldn't. - It is not good practice to intentionally use the same name for variables, even if they exist in different code blocks. - In block scope, a variable is declared inside of a code block, and is only available to code inside that block. Such variables are known as local variables.

JavaScript - Truthy / Falsey

The following all evaluate to true true {} [] 42 “0” “false” new Date() The following all evaluate to false

0
""		empty string
null
undefined
NaN		Not a Number

JavaScript Debugging - General Debugging Strategies

- Determine if only a single user is affected, or multiple users. If only a single user, concentrate on the user's roles. - Determine if only a single instance is affected, or multiple. If a single instance, compare to other instances. - Search for community / knowledge articles. Google “ServiceNow XXX”. - Determine WHEN the issue began, and think about what changed at that time. Looks for bugs in what changed recently. - Use Global Search in quotation marks “XXX” to look for identifiers such as error messages. If that fails, use a Studio Code Search. - Consider using Developer Tools (Client Side Debugging) to look for hidden Errors or Warnings.

JavaScript Debugging - Common Errors

- Using = instead of === to test equality. - Using = instead of : for object property declarations. - Using x to multiply instead of using *. - Forgetting to use parentheses in a function declaration that takes no parameters. - Forgetting to use var in a variable declaration (code may still run, but with unexpected behavior). - Trying to access an array within an array, by using myArray[2,1] instead of myArray[2][1]. - Using line breaks in invalid situations such as between the keyword “return” and an open curly brace ”{“. - Using a semicolon where you do NOT need one, for example after an object property declaration. - Case Sensitivity. Double check the case of every single word in your code. - Using single or double quotes around a piece of code that does not require them.

JavaScript Debugging - Client Side Methods

- Don't forget about the Web Browser Developer Tools (Debugger) for issues related to the Presentation Layer or Network Traffic between the Client and Server. - Many developers use third-party debugging tools when debugging browser-based applications, for example: NG Inspector Chrome Extension - One useful Client-Side debugging technique is to output an object to the HTML by adding an actual HTML tag as follows: <pre>json</pre> - Client Script Debugging Messages - Example Code zGGB_ClientSideDebugMessages - Example Code Execution

aGGB - Test Business Unit 1 


- alert() - confirm()

var bResult = confirm("Are you sure you want to continue?!");
if (bResult){
	alert("OK Clicked");
}
else{
	alert("Cancel Clicked");
}

- console.log OR jslog() - window.status - g_form.addErrorMessage() - g_form.addInfoMessage() - g_form.showFieldMsg()

JavaScript Debugging - Server Side Debugging Methods

gs.addInfoMessage() OR gs.addErrorMessage()

- Very useful for debugging scripts; even server-side scripts for which a web page is displayed.

  1. Messages appear at the top of the form being tested.


gs.info()
  1. Sets Source to “* Script” - Sets log level to “Information”. - Used for informational events, such as messages that describe the progress of the application.
    == gs.error() == - Sets Source to “
    * Script”
  2. Sets log level to “Error”.
  3. Used for critical errors that are encountered.


gs.warn()
  1. Sets Source to “* Script” - Sets log level to “Warning”. - Used to let someone know that there might be a problem. - Can be useful when there are too many other “info” level messages going into the log, as you can filter on just the Warnings.
    == gs.log() == - Global scope. - Sets Source to “
    * Script” Unless a different Source parameter is specified in the 2nd parameter.

- Example Source will be “Phoenix”. Level will be “Information”. gs.log(“GGB1”, “Phoenix”); gs.log(“sValue1: ” + sValue1, “Phoenix”); - View “Phoenix” type log messages in the syslog table, where source == “Phoenix”, here: syslog_with_filter

gs.debug()

- These messages go into the Session Log (not the table “syslog” like the others), and they only go into the Session Log after System Diagnostics - Debug Log is activated.

—-

- They can be seen as follows:


- They also show up underneath forms as follows:

- Note, if you turn on Session Debugging for Business Rules, and you use gs.debug from a business rule, your debug message will NOT show up; You need to turn on the “log” object class, not the “Business Rule” object class. - Useful perhaps for debugging Production issues, or to enable non-developers to see log messages (in rare cases). - These can be turned On or Off for a particular application at Runtime. Create or modify the “application property” with the syntax <app_scope>.logging.verbosity. Set the Value field in the <app_scope>.logging.verbosity property to debug. - The isDebugging() method determines if debugging is active, in script, for a specific scope.


JavaScript Debugging - System Log Module

In the Filter Navigator of ServiceNow, the following Modules show the following records. “System Log” Module Relevant Table Class Level Source All syslog Log Entry Warnings syslog Log Entry Warning Error syslog Log Entry Error Script Log Statements syslog Log Entry *** Script Application Logs syslog_app_scope App Log Entry Transaction Cancellations syslog_cancellation NA


JavaScript Debugging - Code Editor Features

Depending on where you are editing and debugging code, different features will be available to you, as follows: System Location Can Save & Edit Later Has Syntax Highlighting? Can Set Direct Breakpoints Indirect Breakpoints Triggered System Definition - Scripts - Background No No No Yes System Definition - Business Rules Yes Yes Yes Yes “Scheduled Script Executions” / sysauto_script Yes Yes Yes (Requires Custom UI Action) Yes

- In a code editor, type Ctrl + A, and then Shift + Tab to automatically format your code.

JavaScript Debugging - Debugger in ServiceNow / System Diagnostics - Script Debugger

- There is a JavaScript debugger which allows you to set breakpoints and step through code. - There are multiple ways to launch the JavaScript Debugger, as follows, but not all work for all users (for example, if pop-ups are blocked): - From a script editor toolbar, click the JavaScript Debugger button - Use the Application Navigator to open System Diagnostics - Script Debugger - In Studio, open the File - Script Debugger menu item - The Script Debugger must be already running, prior to script execution, in order for execution to be paused at a breakpoint! - Use the Session Log tab in the Script debugger to see a wealth of session debugging information. In the baseline case, no messages appear in the Session Log. Click the Settings icon to select what to log. In the Settings dialog, check the items to log.

- General Approach

1) Set Breakpoint  2) Open Script Debugger  3) Take actions to Trigger Code and Hit Breakpoint  4) Step Through Code

- Debugging - IF you are debugging using the script debugger, an undefined function call, not wrapped in a try/catch block will stop script execution, and all remaining breakpoints will be ignored.

  1. try/catch
    1. Used to trap runtime errors.

- Typical Exception Catching. Can be used along with console.log or jslog() to log a message after you catch an exception. - Breakpoints will NOT be triggered for code that is run asynchronously! You may need to activate the code directly vis Scripts - Background. - Don't forget that you Can set breakpoints in library code, such as in Script Includes!

JavaScript Debugging - Quirks / Gotchas / Stumbling Blocks / Pitfalls

- Debugger - It is NOT necessary to close and re-open the debugger if you make a code change. The debugger content will refresh when you execute your code. - Must allow the Script Debugger window to “Show Notifications”? Be sure to select Yes if you are questioned by the browser about this. - When the execution bar of the debugger goes to the top line, I believe that means that an Exception was thrown from code. - If it seems like you can't set a breakpoint, try refreshing your browser page. Your session may have timed out! - Script Debugger Filter is CASE SENSITIVE! Geoff < > GEOFF - Don’t try to edit code in the Script Debugger. :-) - Be sure you SAVE your script after making changes, before running it! - Saving a record WITHOUT making any changes will NOT trigger Business Rules. - Log entries will NOT show up under the System Log (table: syslog) until after your script completes. They are not asynchronous. They will not show up one at a time as you step through your code line by line. - ServiceNow will let you create a Script Include with any name, but unless the name is exactly the same as your Class Definition Within the Script Include, an Exception will be generated when you go to instantiate that class to call methods. - You may need to “Filter Out” some of the garbage from the log in order to see messages you care about. - With Session Log - Business Rules turned on, you can see the order that business rules run.

The log shows you what TYPE of business rules are run, and when each is started and completed.
	==>		Start
	<==		End
	===		Atomic operation, such as a notification that a Rule will be Skipped.

- The ID of the Script Include record is included in a thrown exception. - Scripts Background - For Scripts - Background, you can trigger breakpoints in Script Includes that you call, but you cannot step “out” of the Script Include, and back into your actual Background Script. - There is no concept of Saving the script before you run it.

JavaScript Debugging - Where to view Log Messages

Session Debug Product Documentation - You can “Enable All” for abundant logging at the bottom of each page after page load, or you can enable each object type one-by-one. - The first icon in the Session Log represents the Type of log item; which may be turned ON or OFF under Settings. - System Diagnostics - Session Debug - Disable All - Used, obviously, to disable all Session Logging.

Debugging Review Method: “Session” - Bottom of Form “Session” - JSDebugger Tab “System Log” / syslog Table Shows icons for the Type of debugging item being displayed, such as the paper icon for Log objects? Yes Yes No

Shows Log Levels (Info, Warning, Error)? No Yes - Icons Yes - “Level” column Allows Filtering by Log Level? No Yes Yes Groups log messages into Transactions, showing the number of messages per transaction? No Yes No Has Dynamic Text Filter for Log Messages? No Yes Yes Has useful “Created by” USER field? No No No Sorts Log Messages by Date/Time, down to the Millisecond? Yes Yes No. Messages generated in the same Second, may sometimes be out of order. Allows filtering by the SOURCE of the log message, such as “Script”. No No Yes Needs to be “Turned On” before you take an action, to show logs? And then needs to be Turned Off? Yes Yes No. Has Complete History. Can show logs after-the-fact. “Business Rule” Source included? That is, can you see Business Rule messages along with other messages? Yes Yes No Nice Table Structure with Filters, etc. No No Yes Shows messages generated by a Workflow? ? No ??? Yes


JavaScript Debugging - Workflows in ServiceNow ServiceNow Workflow provides logging in a log exclusive to workflows. It is separate from the System log that is specific to a currently executing Workflow Context. Workflow developers can add log messages to the special Workflow Log using the following:

workflow.info
workflow.warn
workflow.error
workflow.debug (must be enabled via Navigator - Workflow - Administration - Properties - Log Workflow Debug Messages.

A Workflow Context is a workflow's runtime environment. A context is created when a workflow is launched. The context knows which record the workflow was launched for. Contexts are useful for debugging workflows. ServiceNow Workflow is part of the Glide Script Engine and is invoked with the insert, update, delete or cancel of a Glide record. Log entries in the Workflow Log indicate whether they were entered from the Engine or from the Activity. The Script Debugger can pause any server-side script that runs in an interactive transaction such as business rules, script includes, script actions, or UI actions that require a response to proceed. If the GlideSystem method gs.isInteractive() returns True when running the script in context, then the Script Debugger can pause it.

JavaScript Object Notation (JSON)

- A text format for storing and transporting data. - JSON data is written as name/value pairs. - In JSON, values must be one of the following data types: string, number, object, array, Boolean, null - JSON is much easier to parse than XML. It is also shorter. - A lightweight data-interchange format. - Code for reading and generating JSON exists in many programming languages. - A JavaScript program can easily convert JSON data into JavaScript objects. - JavaScript has a built in function for converting JSON strings into JavaScript objects: - JSON.parse() - Example: const txt = '{“name”:“John”, “age”:30, “city”:“New York”}' const obj = JSON.parse(txt); - JavaScript also has a built in function for converting an object into a JSON string: - JSON.stringify() - Example:

	'{"name":"John", "age":30, "car":null}'

jslog - console.log

- Similar to console.log, which writes messages to the JavaScript console window via the web browser's developer tools. But unlike console.log which is available to all end users regardless of their group or role, jslog messages can only be seen by users with the admin role.

j.txt · Last modified: 05/18/2023 08:33 by 127.0.0.1