此问题可能是由于脚本语法错误或JS引擎错误引起的。可以尝试以下几步来解决问题:
检查脚本语法是否正确,可以使用AppleScript编辑器的“验证语法”功能来检查脚本是否有语法错误。
将JS代码放在try-catch块中,以捕捉可能的异常。
代码示例:
try
# 确认JavaScript引擎可用
tell application "System Events" to do JavaScript "return true" in frontmost application
# 执行JavaScript代码
tell application "System Events" to do JavaScript "alert('Hello, World!');" in frontmost application
on error error_message
display alert "Error: " & error_message
end try
代码示例:
# 导入Foundation框架
use framework "Foundation"
# 使用Objective-C的方法
set dateFormatter to current application's NSDateFormatter's new()
dateFormatter's setDateFormat_("yyyy-MM-dd HH:mm:ss")
set nowStr to (dateFormatter's stringFromDate:(current application's NSDate's date()))
# 使用Swift的方法
set str to "Hello, World!"
set upper to current application's NSString's stringWithString_(str)'s uppercaseString()