mcpField
C
client-scripts

client-scripts

github.com/serac-labs开发7758 次安装9 周前更新
代码仓库

关于 client-scripts

面向 ServiceNow 开发者的客户端脚本技能,用于构建浏览器端表单行为。内容涵盖脚本类型、g_form 用法、GlideAjax 通信、验证和性能实践。

主要功能

  1. 01介绍四种客户端脚本类型
  2. 02提供 g_form API 示例
  3. 03讲解 GlideAjax 客户端与服务端模式
  4. 04表单验证和条件字段设置
  5. 05减少服务端调用并优化事件处理

适用场景

  1. 01表单加载时设置默认值
  2. 02字段值变化后更新其他字段
  3. 03验证表单提交
  4. 04通过 GlideAjax 获取服务端数据

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/serac-labs/serac --skill client-scripts

安装后在 Claude Code 中输入/client-scripts确认已加载。

详细介绍

ServiceNow 客户端脚本模式

客户端脚本在用户的浏览器中运行,用于控制表单行为。与服务器端脚本不同,现代浏览器中的客户端脚本可以使用现代 JavaScript(ES6+)。

客户端脚本类型

类型运行时机用途
onLoad表单加载时设置默认值、隐藏/显示字段、初始设置
onChange字段值更改时响应用户输入、级联更新
onSubmit提交表单时保存前验证
onCellEdit编辑列表单元格时验证行内编辑

g_form API

获取和设置值
// Get field value
var priority = g_form.getValue("priority")
var callerName = g_form.getDisplayValue("caller_id") // Reference display value

// Set field value
g_form.setValue("priority", "1")
g_form.setValue("assigned_to", userSysId, "John Smith") // Reference with display

// Clear a field
g_form.clearValue("assignment_group")
字段可见性和状态
// Show/Hide fields
g_form.setVisible("u_internal_notes", false)
g_form.setDisplay("u_internal_notes", false) // Removes from DOM

// Make field mandatory
g_form.setMandatory("short_description", true)

// Make field read-only
g_form.setReadOnly("caller_id", true)

// Disable field (grayed out but visible)
g_form.setDisabled("state", true)
消息和验证
// Field-level messages
g_form.showFieldMsg("email", "Invalid email format", "error")
g_form.hideFieldMsg("email")

// Form-level messages
g_form.addInfoMessage("Record saved successfully")
g_form.addErrorMessage("Please fix the errors below")
g_form.clearMessages()

// Flash a field to draw attention
g_form.flash("priority", "#ff0000", 0) // Red flash
分区和标签
// Collapse/Expand sections
g_form.setSectionDisplay("notes", false) // Collapse
g_form.setSectionDisplay("notes", true) // Expand

// Change field label
g_form.setLabelOf("short_description", "Issue Summary")

常见模式

模式 1:onLoad - 设置默认值
function onLoad() {
  // Only on new records
  if (g_form.isNewRecord()) {
    // Set default priority
    g_form.setValue("priority", "3")

    // Set caller to current user
    g_form.setValue("caller_id", g_user.userID)

    // Hide internal fields from end users
    if (!g_user.hasRole("itil")) {
      g_form.setVisible("assignment_group", false)
      g_form.setVisible("assigned_to", false)
    }
  }
}
模式 2:onChange - 级联更新
function onChange(control, oldValue, newValue, isLoading) {
  // Don't run during form load
  if (isLoading) return

  // When category changes, clear subcategory
  if (newValue != oldValue) {
    g_form.setValue("subcategory", "")
    g_form.clearValue("u_item")
  }

  // Auto-set priority based on category
  if (newValue == "security") {
    g_form.setValue("priority", "1")
    g_form.setReadOnly("priority", true)
  } else {
    g_form.setReadOnly("priority", false)
  }
}
模式 3:使用 GlideAjax 的 onChange
function onChange(control, oldValue, newValue, isLoading) {
  if (isLoading || newValue == "") return

  // Get data from server
  var ga = new GlideAjax("MyScriptInclude")
  ga.addParam("sysparm_name", "getUserDetails")
  ga.addParam("sysparm_user_id", newValue)
  ga.getXMLAnswer(function (response) {
    var data = JSON.parse(response)

    // Update form with server data
    g_form.setValue("location", data.location)
    g_form.setValue("department", data.department)
    g_form.setValue("u_vip", data.vip)

    if (data.vip == "true") {
      g_form.setValue("priority", "1")
      g_form.flash("priority", "#ffff00", 2)
    }
  })
}
模式 4:onSubmit - 验证
function onSubmit() {
  // Validate email format
  var email = g_form.getValue("u_email")
  if (email && !isValidEmail(email)) {
    g_form.showFieldMsg("u_email", "Please enter a valid email", "error")
    return false // Prevent submit
  }

  // Require close notes when resolving
  var state = g_form.getValue("state")
  var closeNotes = g_form.getValue("close_notes")
  if (state == "6" && !closeNotes) {
    g_form.showFieldMsg("close_notes", "Close notes required", "error")
    g_form.setMandatory("close_notes", true)
    return false
  }

  // Confirm before high-priority submission
  var priority = g_form.getValue("priority")
  if (priority == "1") {
    return confirm("This will create a Priority 1 incident. Continue?")
  }

  return true // Allow submit
}

function isValidEmail(email) {
  var regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  return regex.test(email)
}
模式 5:条件必填字段
function onChange(control, oldValue, newValue, isLoading) {
  if (isLoading) return

  // Category "Hardware" requires asset tag
  var isHardware = newValue == "hardware"
  g_form.setMandatory("u_asset_tag", isHardware)
  g_form.setDisplay("u_asset_tag", isHardware)

  // Category "Software" requires application name
  var isSoftware = newValue == "software"
  g_form.setMandatory("u_application", isSoftware)
  g_form.setDisplay("u_application", isSoftware)
}

GlideAjax 模式(服务器通信)

客户端脚本
function onChange(control, oldValue, newValue, isLoading) {
  if (isLoading || !newValue) return

  var ga = new GlideAjax("IncidentUtils")
  ga.addParam("sysparm_name", "getRelatedIncidents")
  ga.addParam("sysparm_ci", newValue)
  ga.getXMLAnswer(handleResponse)
}

function handleResponse(response) {
  var result = JSON.parse(response)

  if (result.count > 0) {
    g_form.addWarningMessage("There are " + result.count + " related open incidents for this CI")
  }
}
服务器脚本包含
var IncidentUtils = Class.create()
IncidentUtils.prototype = Object.extendsObject(AbstractAjaxProcessor, {
  getRelatedIncidents: function () {
    var ci = this.getParameter("sysparm_ci")
    var result = { count: 0, incidents: [] }

    var gr = new GlideRecord("incident")
    gr.addQuery("cmdb_ci", ci)
    gr.addQuery("active", true)
    gr.query()

    result.count = gr.getRowCount()
    while (gr.next()) {
      result.incidents.push({
        number: gr.getValue("number"),
        short_description: gr.getValue("short_description"),
      })
    }

    return JSON.stringify(result)
  },

  type: "IncidentUtils",
})

g_user 对象

// Current user information
var userName = g_user.userName // User name
var userID = g_user.userID // sys_id
var firstName = g_user.firstName // First name
var lastName = g_user.lastName // Last name
var fullName = g_user.getFullName() // Full name

// Role checks
if (g_user.hasRole("admin")) {
}
if (g_user.hasRole("itil")) {
}
if (g_user.hasRoleExactly("incident_manager")) {
} // Exact match, no admin override

// Multiple roles
if (g_user.hasRoleFromList("itil,incident_manager")) {
}

性能最佳实践

1. 尽量减少服务器调用
// ❌ BAD - Multiple GlideAjax calls
onChange: getUserLocation()
onChange: getUserDepartment()
onChange: getUserManager()

// ✅ GOOD - Single call returning all data
onChange: getUserDetails() // Returns location, department, manager
2. 使用 isLoading 参数
function onChange(control, oldValue, newValue, isLoading) {
  // ❌ BAD - Runs during form load
  callServer(newValue)

  // ✅ GOOD - Skip during load
  if (isLoading) return
  callServer(newValue)
}
3. 对快速更改进行防抖处理
var timeout
function onChange(control, oldValue, newValue, isLoading) {
  if (isLoading) return

  clearTimeout(timeout)
  timeout = setTimeout(function () {
    performExpensiveOperation(newValue)
  }, 300) // Wait 300ms for typing to stop
}

常见错误

错误问题解决方案
忘记检查 isLoading脚本在加载时不必要地运行始终检查 if (isLoading) return;
阻塞 onSubmit验证缓慢时 UI 会冻结使用带回调的异步验证
GlideAjax 中没有错误处理失败时无提示添加错误回调
只在一种浏览器中测试出现跨浏览器问题测试 Chrome、Firefox、Edge
直接操作 DOMUI 更新时会失效使用 g_form API

评论

支持 Markdown