Inserting javascript into a field via code without executing the code

Jonas27
Kilo Guru

I want to create a Catalog Item variable via code and in the "default_value" field, there should be the following code:

Jonas27_0-1741099962865.png

 

 


But when I create the Catalog Item variable by code in a UI Policy like this:

 

Jonas27_1-1741100013552.png

 then the "default_value" does not contain

Jonas27_2-1741100039938.png

 

and instead it contains the sys_id of the logged in user.

So is there a way to insert javascript code into the default_value field via code without the code being executed?
10 REPLIES 10

Juhi Poddar
Kilo Patron

Hello @Jonas27 

Try this:

var variable = new GlideRecord('item_option_new');
variable.setValue('default_value', "javascript: 'gs.getUserID()'");
//and some other field values
variable.insert();

Hope this helps!

 

"If you found my answer helpful, please like and mark it as an "accepted solution". It helps future readers to locate the solution easily and supports the community!"

 

Thank You
Juhi Poddar

Jonas27
Kilo Guru

Thanks for the proposed solution, but this

Jonas27_0-1741101046689.png

leads to only "gs.getUserID()" getting inserted into the default_value field, so without the javascript part at the beginning.

Hello @Jonas27 

  • You cannot directly insert JavaScript code into the default_value field of a Catalog Item variable without it being executed.
  • ServiceNow automatically processes certain script prefixes, like javascript:, when the variable is loaded.

Hope this helps!

 

"If you found my answer helpful, please like and mark it as an "accepted solution". It helps future readers to locate the solution easily and supports the community!"

 

Thank You
Juhi Poddar

Vishal Jaswal
Giga Sage

Hello @Jonas27 

To achieve something like below, use a "Custom with Label" Type field with default value as javascript:gs.getUserID() or if you want to use a text field then wrap the default value in single or double quotes: 'javascript:gs.getUserID()'

vishal_jaswal_1-1741104866171.png

vishal_jaswal_2-1741104895874.png

vishal_jaswal_3-1741104957927.png

 

 

 


Hope that helps!