JavaScript Reference Guide
JavaScript Reference Guide
bc JavaScript
Reference Guide
http://partners.adobe.com
October 2003
ii
Channel.......................................................................................116
Channels .....................................................................................117
CMYKColor ...............................................................................123
DCS1_SaveOptions ...................................................................124
DCS2_SaveOptions ...................................................................125
Document ...................................................................................126
DocumentInfo............................................................................134
Documents .................................................................................138
EPSOpenOptions.......................................................................139
EPSSaveOptions ........................................................................140
ExportOptionsIllustrator..........................................................141
GalleryBannerOptions..............................................................142
GalleryCustomColorOptions ..................................................143
GalleryImagesOptions..............................................................144
GalleryOptions ..........................................................................145
GallerySecurityOptions............................................................146
GalleryThumbnailOptions.......................................................147
GIFSaveOptions ........................................................................148
GrayColor...................................................................................149
HistoryState ...............................................................................150
HistoryStates..............................................................................151
HSBColor....................................................................................152
IndexedConversionOptions ....................................................153
JPEGSaveOptions......................................................................154
LabColor .....................................................................................155
LayerComp ................................................................................156
LayerComps...............................................................................157
Layers..........................................................................................158
LayerSet ......................................................................................159
LayerSets ....................................................................................162
PathItem .....................................................................................164
PathItems....................................................................................177
PathPoint ....................................................................................178
PathPointInfo .............................................................................179
PathPoints ..................................................................................180
PDFOpenOptions......................................................................181
PDFSaveOptions .......................................................................182
PhotoCDOpenOptions .............................................................183
PhotoshopSaveOptions ............................................................184
JavaScript Reference Guide v
PICTFileSaveOptions................................................................185
PICTResourceSaveOptions......................................................186
PixarSaveOptions......................................................................187
PNGSaveOptions ......................................................................188
Preferences .................................................................................189
PresentationOptions .................................................................193
RawFormatOpenOptions.........................................................194
RawSaveOptions .......................................................................195
RGBColor ...................................................................................196
Selection......................................................................................197
SGIRGBSaveOptions ................................................................205
SolidColor...................................................................................206
SubPathInfo................................................................................207
SubPathItem...............................................................................208
SubPathItems .............................................................................209
TargaSaveOptions.....................................................................210
TextFont......................................................................................211
TextFonts ....................................................................................212
TextItem......................................................................................213
TiffSaveOptions.........................................................................217
xmpMetadata.............................................................................218
Index ..............................................................................................................245
vi JavaScript Reference Guide
1
Introduction
This reference guide describes the objects and commands in the Adobe® Photoshop® CS
JavaScript type library. In addition to this Introduction, it includes the following sections:
In the object model illustrated below, the Photoshop Application object sits at the top of the
containment hierarchy. The Document object, directly below the Photoshop application, is the
active object you are working with and the gateway to the main components of the Photoshop
object model.
1
2 JavaScript Reference Guide
The Document class is used to make modifications to the document image. By using the Document
object you can crop, rotate or flip the canvas, resize the image or canvas, and trim the image. You
could also use the Document object to get the active layer, for example, save the current document,
then copy and paste within the active document or between different documents.
Application
Object Model Classes
Document
Selection Class
The Selection class is used to specify an area of pixels in the active document (or in a selected layer
of the active document) that you want to work with.
Channel Class
The Channel class is used to store pixel information about an image’s color. Image color
determines the number of channels available. An RGB image, for example, has four default
channels: one for each primary color and one for editing the image. You could have the red
channel active in order to manipulate just the red pixels in the image, or you could choose to
manipulate all the channels at once.
These kinds of channels are related to the document mode and are called “component channels. In
addition to the component channels, Photoshop lets you to create additional channels. You can
create a “spot color channel”, a “masked area channel” and a “selected area channel.”
Using the methods of a Channel object, you can create, delete and duplicate channels or retrieve a
channel's histogram and change its kind or change the current channel selection.
JavaScript Reference Guide 3
Layer Classes
Photoshop has 2 types of layers: an art layer that can contain image contents and a layer set
that can contain zero or more art layers.
An Art Layer is a layer class within a document that allows you to work on one element of an
image without disturbing the others. Images are typically composed of multiple layers (see Layer
Set, below). You can change the composition of an image by changing the order and attributes of
the layers that comprise it.
A Text Item is a particular type of art layer that allows you to add type to an image. In Photoshop,
a text item is implemented as a property of the art layer.
A Layer Set is a class that comprises multiple layers. Think of it as a folder on your desktop. Since
folders can contain other folders, a layer set is recursive. That is, one layer set may call another
layer set in the Object Model hierarchy.
History Class
The History class is a palette object that keeps track of changes made to a document. Each time
you apply a change to an image, the new state of that image is added to the palette. These states
are accessible from document object and can be used to reset the document to a previous state. A
history state can also be used to fill a selection.
In AppleScript, if you create a document and then immediately try to get history state, Photoshop
returns an error. You must first activate Photoshop -- make it the front-most application -- before
you can access history states.
Not shown in the Object Model are collections. A collection is a convenient way of grouping
classes. Not all classes are associated with a collection.
4 JavaScript Reference Guide
Open
Open Classes Options
In Visual Basic and JavaScript, the SolidColor object handles all colors. The solid color classes
available in Photoshop are illustrated below.
New in Photoshop CS
This section gives a brief overview of some important new JavaScript additions to the
Photoshop application.
This framework allows developers to use JavaScript to create UI components such as windows,
panels, buttons, checkboxes and so on. The framework -- called the scripting user interface -- is
built as an abstraction layer on top of the windowing framework provided by the host platform on
which Photoshop CS is running. Both Windows and MAC OS X native windowing systems are
supported. For more information, see Chapter 2, Creating User Interface Elements.
Depending on the platform, fileRef’s system-local path (.fsName) would look something like:
JavaScript but will enhance your ability to take advantage of Photoshop features. These directives
are embedded in JavaScript comments and are as follows:
//@includepath <pathSpecification>
The path or paths which the JavaScript interpreter will “walk” looking for a script specified in a /
/@include statement. If using //@includepath, the name of the script provided in the //@include
statement should either be the name only without path qualifier or with a relative path. Multiple
paths can be provided, separated by semi-colons. Given this:
//@includepath "~;../../FolderTwoLevelsUp"
//@include "jsLibrary.js"
//@include "libraries/otherLibrary.js"
‘otherLibrary.js’ will be searched for in the same way, except that the directory/folder ‘libraries’
must be found in one of the search locations. The first match encountered will be loaded, so care
must be taken when specifying the search order to ensure that the intended version of the file is
found first.
//@include fileSpecification
The relative or fully qualified path/scriptname to include. The script is included inline into the
active script, so care must be taken to ensure that variable names and function definitions in the
included script do not collide with the active script. Inclusion occurs before the active script is
evaluated. Note that lines numbers displayed in the debugger relate to the entire composite script,
not the original line numbers of the active and included script – again, because the included file is
not treated as a separate module but is rather included directly inline.
//@show include
If a script has been included in the active script, its code is not shown by default in the debugger.
This statement
JavaScript Reference Guide 7
A JavaScript framework for creating User Interface (UI) elements is included in Photoshop CS.
This framework allows developers to use JavaScript to create UI components such as windows,
panels, buttons, checkboxes and so on. The framework -- called the scripting user interface -- is
built as an abstraction layer on top of the windowing framework provided by the host platform on
which Photoshop CS is running. Both Windows and MAC OS X native windowing systems are
supported.
The motivation behind the creation of this scripting user interface was twofold:
• To enable JavaScripts to create dialogs and interact with controls. This satisfies a
fundamental need on the part of developers to create parameterized scripts, whose actions
can be controlled more directly by the end user.
• To extend the JavaScript environment to allow scripts to create UI elements dynamically. In
this way, developers can create specialized interactive access to an application’s
functionality.
• dialog -- a modal dialog box. Photoshop CS supports modal dialogs only. Modeless
dialogs, such as palettes, are not supported.
• Panels (frames) -- (classname Panel) a container to group and organize other control types
• Push buttons -- (classname Button) a button containing a text string
• Radio buttons-- (classname RadioButton) a dual-state control, usually grouped with other
radio buttons, only one of which is set
• Checkbox buttons -- (classname Checkbox) a dual-state control showing a checked box (if
true) or an empty box (if false)
9
10 JavaScript UI Interface Introduction
• Edit text -- (classname EditText) an text field that the user can change.
• Static text -- (classname StaticText) a text field that the user cannot change
• Scrollbars -- (classname Scrollbar) a standard scrollbar with a moveable element and
stepper buttons to incrementally move the element.
• Sliders -- (classname Slider) a standard slider with a moveable position indicator
In addition, the given classnames described above can used in window resource specifications to
define controls within a window or panel. See “Creating a window using window resource
specifications” on page 18 for more information.
JavaScript UI Interface
This section provides a description of the scripting user interface programming model.
UI Objects
The scripting user interface defines Window objects that wrap native windows and various control
elements (Buttons, StaticText, etc.), which wrap simple native controls. These objects share
common methods such as “query the element type”, “move the elements around”, and “set the
title, caption or content”. For a complete list of properties and methods, see “JavaScript UI
Reference” on page 30
Creating a window
To create a new window, use the Window constructor function. The constructor takes the desired
type of the window (dialog) as a parameter. You can supply optional arguments to specify an
initial window title and bounds.
The code examples provided in the JavaScript Interface section consist of short segments from a
complete script that is included later in this document. The examples presented build upon
each other.
The following example creates an empty dialog with the variable name dlg. This dialog is carried
though to subsequent examples:
// Create an empty dialog window near the upper left of the screen var
var dlg = new Window('dialog', 'Alert Box Builder', [100,100,480,245]);
dlg.show();
JavaScript Reference Guide JavaScript UI Interface 11
Note: Newly created windows are initially invisible; the show() method makes them visible.
Roughly speaking, the numeric parameters to the constructor correspond to the top left and
bottom right coordinates of the window. The bounds supplied when creating the dialog specify the
requested size of the client area, which is the area of the dialog on which you can create controls. It
does not include the title bar and borders around the client area. The size and position of the
dialog as a whole are automatically adjusted to maintain the requested client area size.
For a more detailed description of window bounds, see “Element size and location” on page 11.
Container elements
All windows are containers, which is to say they contain other elements such as panels, buttons
and checkboxes within their boundaries.
Within a window, you can create other types of container elements and add interface components
to them, just like you add elements to a window (see “Adding elements” on page 12). Elements
added to a container are considered children of that container and certain operations performed
on a container element also apply to its children. For instance, calling the container’s hide() method
makes the container invisible and makes all of its visible children invisible as well.
Along the same lines, calling the container’s show() method makes the container visible as well as
any child elements that were visible before the container was hidden. The following properties
and methods of containers also apply to all children of that container: visible, enabled, hide(), show().
The location of an element within a window or other container element is defined as the point
where the top left corner of an element is specified in the window coordinate system, relative to
the container the element lies within. Size is specified by width and height in pixels. A complete
bounds specification therefore consists of 4 integer values which define the position of the upper
left corner of the object and its dimensions.
12 JavaScript UI Interface Introduction
The value of the bounds property can take several forms: a string with special contents, an inline
JavaScript “Bounds” object, or a four-element array. The following examples show equivalent
ways of placing a 380 by 390 pixel window near the upper left corner of the screen:
Note that the window dimensions define the size of the “client area” of the window, which is the
portion of the window that an application can directly control. The actual window size will
typically be larger, because the host platform’s window system can add title bars and borders to
windows.
When read, the bounds property returns a Bounds object -- an array of four values representing the
coordinates of the upper left and lower right corners of the element: [left, top, right, bottom].
Adding elements
To add elements to a window or other container, use the container’s add() method. This method
accepts the type of the element to be created and some optional parameters, depending on the
element type. The return value is the UI object created or null on errors. The value of the element’s
visible property defaults to “true”.
element is initially visible, but it will remain invisible as long as its parent object is invisible.
A second (optional) parameter may be used to specify the initial bounds. The bounds is relative to
the working area of its parent container. For elements which display text, the text may be specified
as the third (optional) parameter -- other types of elements have different semantics for a third
argument.
For more information on the way in which each type of element interprets optional parameters,
“JavaScript UI Reference” on page 30. These optional parameters are positional, meaning that if
you want to specify some text for an element, but don’t care about its bounds, you must still
provide an argument for the second parameter in order to supply a value for the third (text)
parameter. You can ‘skip over’ a positional parameter by specifying the ‘undefined’ value as its
argument value. In the example below, a Button element is created with an initial text value, but
no bounds value.
Dynamically creating a property such as btnPnl to reference the control object returned by add()
is not required, but can make it easier to later refer to the control. See “Accessing child elements”
on page 13 for more information.
JavaScript Reference Guide JavaScript UI Interface 13
Creation properties
Some element types have attributes that may only -- in fact -- can only be specified when the
element is created. These are not normal properties of the element, in that they cannot be changed
during the element’s lifetime, and they are only needed once. For these element types, an optional
creation properties argument may be supplied to the add() method -- this argument is an object with
one or more properties that controls things like the element’s appearance, or special functions like
‘read-only’ for an edit text element.
All UI elements have a creation property called name, which can be used to assign a name for
identifying that element. In the following example, the new Button element is assigned the
name ‘ok’:
The children collection is an array containing every defined element, indexed from 0 to the
number of elements minus 1. For controls or other elements that do not have children, the children
collection is empty.
The number of child elements in a window is equal to the value of the length property of the
children collection. In the example below, since the ‘msgPnl’ panel was the first element created in
dlg, the text for the panel’s title can be set as follows:
Using creation properties, a name can be assigned to a newly created element. If this is done, a
child can be referred to by its name. For instance, the Button in the example in the previous section
was named ‘ok’, so the Button could now be referred to like this:
dlg.btnPnl.children[‘ok’].text = “Build”;
14 JavaScript UI Interface Introduction
An even simpler way to refer to a named child element is to use its name as a property of its parent
element. We can also refer to the Button from the previous example like this:
dlg.btnPnl.ok.text = “Build”;
The value of an element’s internal name property is used by the scripting user interface when a
script accesses a property of the element’s parent object that does not match any of the predefined
properties.
In this case, the framework searches the names of the parent element’s children to see if a match
exists, and if so, returns a reference to the matching child object.
Types of UI Elements
This section introduces the types of user interface elements you can create within a Window or
other type of container element.
You can also use panels as separators: panels with width = 0 appear as vertical lines and panels
with height = 0 appear as horizontal lines. When you create a Panel, you can specify an optional
borderStyle property (used only at creation time) to control the appearance of the border drawn
around the panel.
dlg.show();
The textselection property can be assigned to in order to replace the current selection with new text,
or to insert text at the cursor (insertion point). It can be read from to obtain the current selection,
if any.
Using the same panel pictured above, the example now adds some EditText elements, with initial
values that a user can accept or replace:
Note the creation property on the second EditText field, where multiline:true is specified.
multiline:true indicates that the text in the item should wrap to the next page. In other words, it
specifies a field in which a long text string may be entered, and the text will wrap to appear as
multiple lines.
16 JavaScript UI Interface Introduction
When it is clicked, it changes its appearance, either showing a checkmark in the box area, or
showing an empty box. When the checkmark appears, the state of the value property is true, and
when the box is empty, the state of the value property is false. When you create a Checkbox, you can
set its value property to specify its initial state and appearance.
A RadioButton is similar to a Button; it can be clicked by a user, and it has a text property to specify
an identifying text string that appears next to the button. Like a Checkbox, it has a value property
that has a Boolean value, representing the state of that button.
You group a related set of RadioButtons by creating all the related elements one after another. The
elements in a group interact with one another. Only one button’s value can be true, and its
appearance differs from others in the same group. Setting a different button’s value property true
changes the state of the button whose state was previously true to false. When you create a group
of RadioButtons, you should set the state of one of them true:
A Slider has a value property that reflects the position of the moveable indicator, and minvalue and
maxvalue properties to define the endpoints of the slider’s range of values.
To make a slider control appear like those used in Photoshop, adjust the height of the control until
the slider bar appears as a single line.
addition, they have ‘stepper buttons’ at each end of the scrollbar for moving the position indicator
in fixed-size steps.
You can control the size of each ‘step’ by setting the stepdelta property. Clicking the mouse pointer
ahead of or behind the position indicator makes the position indicator jump a fixed number of
values toward the point where you clicked. You can control the size of this ‘jump’ by setting the
jumpdelta property.
You can create scrollbars with horizontal or vertical orientation; if width is > height, the
orientation is horizontal, otherwise it is vertical. The following example creates a Scrollbar element
with associated StaticText and EditText elements within a panel:
Note that the last 3 arguments to the add() method that creates the scrollbar define the values for
the value, minvalue and maxvalue properties. Scrollbars are often created with an associated EditText
field to display the current value of the scrollbar, and to allow setting the scrollbar’s position to a
specific value.
The special string is passed as the type parameter to the Window constructor function, as follows:
alignCenterRb:RadioButton { text:’Center’, \
bounds:[105,15,185,35] }, \
alignRightRb:RadioButton { text:’Right’, bounds:[195,15,275,35] } \
}, \
sizePnl: Panel { text: ‘Dimensions’, bounds:[60,240,320,315], \
widthSt:StaticText { text:’Width:’, bounds:[15,15,65,35] }, \
widthScrl:Scrollbar { minvalue:300, maxvalue:800, \
bounds:[75,15,195,35] }, \
widthEt:EditText { bounds:[205,15,245,35] }, \
heightSt:StaticText { text:’Height:’, bounds:[15,45,65,65] }, \
heightScrl:Scrollbar { minvalue:200, maxvalue:600, \
bounds:[75,45,195,65] }, \
heightEt:EditText { bounds:[205,45,245,65] } \
}, \
btnPnl: Panel { text: ‘Build it’, bounds:[15,330,365,375], \
testBtn:Button { text:’Test’, bounds:[15,15,115,35] }, \
buildBtn:Button { text:’Build’, bounds:[125,15,225,35], \
properties:{name:’ok’} }, \
cancelBtn:Button { text:’Cancel’, bounds:[235,15,335,35], \
properties:{name:’cancel’} } \
} \
}”;
dlg = new Window (alertBuilderResource);
Note: This example creates the same dialog as the complete example script described in
“JavaScript UI Example” on page 24, using a resource specification instead of explicit calls to the
add() method of a container element.
The general structure of a window resource specification is a Window type specification (i.e.,
“dialog”), followed by a set of braces enclosing one or more property definitions. Controls are
defined as properties within windows and other containers by specifying the classname of the
control in a property definition, with properties of the control enclosed in braces {}, for example:
testBtn: Button { text: ‘Test’ }.
Creation properties are specified in a properties property as named properties of an inline object (see
example above). The syntax of window resource specification strings is completely described
below.
Note: To create a UI element, the classname in the namedObject definition above can be any
element classname referred to in “Types of Interface Elements” on page 9. For example:
“dialog { \
text: ‘From Resource’, bounds: [10, 10, 210, 110], \
box: Panel { \
bounds: [10, 10, 190, 90], \
ok: Button { \
text: ‘OK’, bounds:[40, 30, 140, 50], \
} \
} \
}”;
These user actions or manipulations generate events within the user interface system. The script
that creates a window needs a way to be notified of events from that window or from controls
within the window. The scripting user interface provides a number of event callback methods that a
script can define as properties of any UI element that the script needs to interact with.
Each class of UI element has a set of callback methods defined for it. For windows, there are
callbacks like onClose(), onMove(), and onResize(). For controls, callbacks vary from type to type. A
typical callback is onClick() for button, radiobutton, and checkbox elements, and onChange() for
edittext fields, scrollbars, and sliders.
To handle a given event for some UI element, simply define a property of the same name as the
event callback in the element and assign a JavaScript function you have defined to it. The example
below uses "in line" functions, which employ a unique syntax and do not require a name.
However, you can also define the function elsewhere in the script. In that case, simply assign the
name of the function to the event handler property. The scripting user interface calls these
functions on event notifications if defined.
JavaScript Reference Guide JavaScript UI Interface 21
Examples:
Because event callback functions work as methods of the object in which they are defined, the
functions have access to the object via the “this” JavaScript keyword. In the examples above,
“this” refers to the UI object a given callback is defined in, so properties of the UI object can be
accessed relative to the “this”. For example, because each UI object has a parent property which is
a reference to its container object, this.parent gets you a reference to the object’s parent object.
To elaborate further on this point, a button( ) is contained within a panel, which is contained within
a window, all of which are ultimately closed. The progression is from smaller to larger UI moving
from left to right.
buildBtn.onClick = function () {this.parent.parent.close(1);};
button
panel
dialog
Also be aware that you can simulate user actions by sending an event notification directly to a UI
element, via the element’s notify() method. In this manner, a script can generate events in the
controls of a window, as if a user was clicking buttons, entering text, moving a window, etc.
radiobutton and checkbox elements have a boolean value property; using notify() to simulate a click
on these elements also changes the value of this property, just like clicking the element would do.
For instance, if the value of a checkbox ‘hasBtnsCb’ in our example above is true, the following
example changes the value to false:
if (dlg.hasBtnsCb.value == true)
dlg.hasBtnsCb.notify();
// dlg.hasBtnsCb.value is now false
A complete description of the different event callback methods and notify() can be found in
the“Common Methods and Event Handlers” on page 35.
22 JavaScript UI Interface Introduction
Modal dialogs
A modal dialog is initially invisible. When calling its show() method, the dialog is displayed and
starts executing. The call to show() does not return until the dialog has been dismissed, typically by
the user clicking an OK or Cancel button.
When calling the hide() or close() methods during the execution of a modal dialog, the dialog is
dismissed. The close() method accepts an optional argument that the call to show() returns.
Warning: You cannot use the JavaScript debugger to debug event callback functions for modal dialogs,
because once the dialog starts executing, it captures all mouse events. Setting a breakpoint in an event
callback function for a modal dialog will result in an apparent application hang if the breakpoint is ever
reached.
To work around this restriction, an effective debugging technique is to create your dialog, but not call its
show() method to make it visible. Then use the debugger to call the notify() method on controls whose event
callback functions you wish to debug. It’s considered good design practice to keep the code in the event
callback functions simple, while deferring the primary script logic execution until after the dialog has been
dismissed.
The scripting user interface provides reasonable defaults if the defaultElement and cancelElement
properties are still undefined when the dialog is about to be shown for the first time.
Default values for the defaultElement property are determined by the following algorithm:
• The scripting user interface searches the dialog’s buttons for a button whose name property
has the string value ‘ok’ (case is not important). If one is found, defaultElement is set to that
object.
• If no matching named object is found, The scripting user interface searches the dialog’s
buttons for a button whose text property has the string value ‘ok’ (case is not important). If
one is found, defaultElement is set to that object.
Default value for the cancelElement property are determined by the following algorithm:
JavaScript Reference Guide JavaScript UI Interface 23
• The scripting user interface searches the dialog’s buttons for a button whose name property
has the string value ‘cancel’ (case is not important). If one is found, cancelElement is set to that
object.
• If no matching named object is found, the scripting user interface searches the dialog’s
buttons for a button whose text property has the string value ‘cancel’ (case is not important).
If one is found, cancelElement is set to that object.
These algorithms handle most dialog boxes without the designer having to explicitly set these
properties. When you add buttons to a dialog that will be used to dismiss the dialog, use creation
properties to set the name property of such buttons to ‘ok’ or ‘cancel’, depending on the desired
semantics; this precaution makes the above algorithm work properly even when the text of such
buttons is localized. If the scripting user interface cannot find a matching button for either case,
the respective property is set to null, which means that keyboard shortcuts for default or cancel
will not notify any elements.
• onChange() functions are needed for edittext elements, if users enter values which must be
validated (like a number within a range). The event callback must perform any necessary
validation, and interact with the user on errors.
• Define onClick() for OK and Cancel buttons which close the dialog with a given value.
Note: Perform this function only if you have not defined the defaultElement and/or
cancelElement properties or named these buttons in such a way that they will automatically be
identified as the "OK" and "Cancel" buttons.
The scripting user interface defines functions alert(), confirm() and prompt() on the Window class
that provides this standard functionality. The host application controls the appearance of these
simple dialog boxes, so they are consistent with other alert and message boxes displayed by the
application. See the “JavaScript UI Reference” on page 30 for details.
24 JavaScript UI Example Introduction
JavaScript UI Example
Having explored the individual scripting components that make up the user interface, you are
now ready to see the parts assembled into real-world JavaScript code that produces a fully
functional user interface.
The JavaScript UI code sample described below includes the following functions, which creates a
simple user interface builder window populated with various panels, checkboxes, buttons and
controls. When you run the builder, you can then cause it to create an Alert Box.
• createBuilderDialog() -- Creates an empty dialog window near the upper left of the screen and
adds a title panel, a checkbox, a control panel and a panel with buttons to test parameters
and create the Alert Box specification.
• initializeBuilder() --Sets up initial control states and attaches event callback functions to
controls.
• runBuilder() -- Runs the builder dialog and returns the resulting Alert Box UI
• createResource() -- Creates and returns a string containing a dialog resource specification that
creates the Alert Box UI using the parameters entered
• stringProperty() -- Returns a formatted string
• arrayProperty() -- Returns a formatted array
• createTestDialog() -- Creates a new Test dialog
These functions are bundled together into a Main script, which assembles the final Alert Box
dialog.
JavaScript Reference Guide JavaScript UI Example 25
createBuilderDialog
Most of the heavy-lifting for visual components of the JavaScript UI code sample occurs in the
createBuilderDialog() function, where the main components of the dialog are configured, as
displayed below.
function createBuilderDialog()
{
//Create an empty dialog window near the upper left of the screen
var dlg = new Window('dialog', 'Alert Box Builder', [100,100,480,490]);
1
//Add a panel to hold title and 'message text' strings
dlg.msgPnl = dlg.add('panel', [25,15,355,130], 'Messages');
dlg.msgPnl.titleSt = dlg.msgPnl.add('statictext', [15,15,105,35], 'Alert box title:');
dlg.msgPnl.titleEt = dlg.msgPnl.add('edittext', [115,15,315,35], 'Sample Alert');
dlg.msgPnl.msgSt = dlg.msgPnl.add('statictext', [15,65,105,85], 'Alert message:');
dlg.msgPnl.msgEt = dlg.msgPnl.add('edittext', [115,45,315,105], '<your message here>',
{multiline:true});
//Add a checkbox to control the presence of buttons to dismiss the alert box
dlg.hasBtnsCb = dlg.add('checkbox', [125,145,255,165], 'Has alert buttons?'); 2
//Add panel to determine alignment of buttons on the alert box
dlg.alertBtnsPnl = dlg.add('panel', [45,180,335,225], 'Button alignment');
dlg.alertBtnsPnl.alignLeftRb = dlg.alertBtnsPnl.add('radiobutton', [15,15,95,35], 'Left');
dlg.alertBtnsPnl.alignCenterRb = dlg.alertBtnsPnl.add('radiobutton', [105,15,185,35],
'Center');
dlg.alertBtnsPnl.alignRightRb = dlg.alertBtnsPnl.add('radiobutton', [195,15,275,35], 'Right');
//Add a panel with controls for the dimensions of the alert box
dlg.sizePnl = dlg.add('panel', [60,240,320,315], 'Dimensions');
dlg.sizePnl.widthSt = dlg.sizePnl.add('statictext', [15,15,65,35], 'Width:');
dlg.sizePnl.widthScrl = dlg.sizePnl.add('scrollbar', [75,15,195,35], 300, 300, 800);
dlg.sizePnl.widthEt = dlg.sizePnl.add('edittext', [205,15,245,35]);
3
dlg.sizePnl.heightSt = dlg.sizePnl.add('statictext', [15,45,65,65], 'Height:');
dlg.sizePnl.heightScrl = dlg.sizePnl.add('scrollbar', [75,45,195,65], 200, 200, 600);
dlg.sizePnl.heightEt = dlg.sizePnl.add('edittext', [205,45,245,65]);
//Add a panel with buttons to test parameters and create the alert box specification
dlg.btnPnl = dlg.add('panel', [15,330,365,375], 'Build it');
dlg.btnPnl.testBtn = dlg.btnPnl.add('button', [15,15,115,35], 'Test');
4
dlg.btnPnl.buildBtn = dlg.btnPnl.add('button', [125,15,225,35], 'Build', {name:'ok'});
dlg.btnPnl.cancelBtn = dlg.btnPnl.add('button', [235,15,335,35], 'Cancel', {name:'cancel'});
return dlg;
} // createBuilderDialog
26 JavaScript UI Example Introduction
This code snippet, when broken down into smaller segments -- and run in the context of the
entire UI sample code that follows -- produces the following succession of dialogs, which
coalesce into one final Alert Box window.
Final Dialog
Created
JavaScript Reference Guide JavaScript UI Example 27
For the final dialog to actually display, supporting code to initialize and run the Alert Box Builder
must be included, as illustrated below.
function initializeBuilder(builder)
{
//Set up initial control states
with (builder) {
hasBtnsCb.value = true;
alertBtnsPnl.alignCenterRb.value = true;
with (sizePnl) {
widthEt.text = widthScrl.value;
heightEt.text = heightScrl.value;
}
}
builder.hasBtnsCb.onClick =
function () { this.parent.alertBtnsPnl.enabled = this.value; };
with (builder.btnPnl) {
//The Test button creates a trial Alert box from the current specifications
testBtn.onClick =
function () {
Window.alert('Type Enter or Esc to dismiss the test Alert box');
createTestDialog(createResource(this.parent.parent));
};
function runBuilder(builder)
{
//Run the builder dialog, return its result
return builder.show();
}
function createResource(builder)
{
//Define the initial part of the resource spec with dialog parameters
var dlgWidth = Number(builder.sizePnl.widthEt.text);
var dlgHeight = Number(builder.sizePnl.heightEt.text);
var res = "dialog { " +
28 JavaScript UI Example Introduction
stringProperty("text", builder.msgPnl.titleEt.text) +
arrayProperty("bounds", 0, 0, dlgWidth, dlgHeight) +
"\n";
//Define the alert message statictext element, sizing it to the alert box
var margin = 15; var l, t;
var msgWidth, msgHeight;
var hasButtons = builder.hasBtnsCb.value;
var btnsHeightUsed = hasButtons ? 20 + margin : 0;
msgHeight = 60;
msgWidth = dlgWidth - (margin * 2);
l = margin;
t = (dlgHeight - msgHeight - btnsHeightUsed) / 2;
res += " msg: StaticText { " +
stringProperty("text", builder.msgPnl.msgEt.text) +
arrayProperty("bounds", l, t, l + msgWidth, t + msgHeight) +
"justify:'center', properties:{multiline:true} }";
//All done!
res += "\n}";
return res;
}
function arrayProperty(pname, l, t, r, b)
{
return pname + ":[" + l + "," + t + "," + r + "," + b + "], ";
}
function createTestDialog(resource)
{
var target = new Window (resource);
return target.show();
}
if (runBuilder(builder) == 1) {
//Create the Alert dialog resource specification string
var resSpec = createResource(builder);
//Write the resource specification string to a file, using the standard file open dialog
var fname = File.openDialog('Save resource specification');
var f = File(fname);
if (f.open('w')) {
var ok = f.write(resSpec);
if (ok)
ok = f.close();
if (! ok)
Window.alert("Error creating " + fname + ": " + f.error);
}
}
Note: This is a complete example of a resource specification string. The alertBuilderResource() code
displayed below is a way to create the same main dialog box created by the createBuilderDialog()
function.
30 JavaScript UI Reference Introduction
var alertBuilderResource =
"dialog { text: 'Alert Box Builder', bounds:[100,100,480,490], \
msgPnl: Panel { text: 'Messages', bounds:[25,15,355,130], \
titleSt:StaticText { text:'Alert box title:', bounds:[15,15,105,35] }, \
titleEt:EditText { text:'Sample Alert', bounds:[115,15,315,35] }, \
msgSt: StaticText { text:'Alert message:', bounds:[15,65,105,85] }, \
msgEt: EditText { text:'<your message here>', bounds:[115,45,315,105],
properties:{multiline:true} } \
}, \
hasBtnsCb: Checkbox { text:'Has alert buttons?', alignment:'center',
bounds:[125,145,255,165] }, \
alertBtnsPnl: Panel { text:'Button alignment', bounds:[45,180,335,225], \
alignLeftRb:RadioButton { text:'Left', bounds:[15,15,95,35] }, \
alignCenterRb:RadioButton { text:'Center', bounds:[105,15,185,35] }, \
alignRightRb:RadioButton { text:'Right', bounds:[195,15,275,35] } \
}, \
sizePnl: Panel { text: 'Dimensions', bounds:[60,240,320,315], \
widthSt:StaticText { text:'Width:', bounds:[15,15,65,35] }, \
widthScrl:Scrollbar { minvalue:300, maxvalue:800, bounds:[75,15,195,35] }, \
widthEt:EditText { bounds:[205,15,245,35] }, \
heightSt:StaticText { text:'Height:', bounds:[15,45,65,65] }, \
heightScrl:Scrollbar { minvalue:200, maxvalue:600, bounds:[75,45,195,65] }, \
heightEt:EditText { bounds:[205,45,245,65] } \
}, \
btnPnl: Panel { text: 'Build it', bounds:[15,330,365,375], \
testBtn:Button { text:'Test', bounds:[15,15,115,35] }, \
buildBtn:Button { text:'Build', bounds:[125,15,225,35], properties:{name:'ok'} }, \
cancelBtn:Button { text:'Cancel', bounds:[235,15,335,35], properties:{name:'cancel'} } \
} \
}";
function createBuilderDialogFromResource()
{
//Create from resource
return new Window(alertBuilderResource);
} // createBuilderDialogFromResource
JavaScript UI Reference
The JavaScript user interface defines the global elements of the Window object and properties and
methods of all the UI classes.
To call class methods, use the following example syntax: Window.alert("Class method!");
JavaScript Reference Guide JavaScript UI Reference 31
alert (text)
Displays the specified string in a user alert box that provides an OK button. The alert dialog is
not intended for lengthy messages. When the string argument to the alert method is too long,
the alert dialog truncates it.
confirm (text)
Displays the specified string in a self-sizing modal dialog box that provides Yes (default) and
No buttons. When this user clicks one of these buttons, this method hides the dialog and
returns a value indicating the button the user clicked to dismiss the dialog. A return value of
true indicates that the user clicked the Yes button to dismiss the confirm box. The confirmation
dialog displays lengthier messages than the alert and prompt dialogs do, but if this string is
too long, the dialog truncates it.
find (type, title)
return value: Object
Finds an existing window already created by a script. title is the title of the window and type is
modal dialog. This value is a hint in case more than one window has the same title; if the type
is unimportant, null or an empty string can be passed. If the window was found, the
corresponding JavaScript Window object is generated and returned; if the window cannot be
determined, the return value is null.
prompt (prompt [, default])
Displays a modal dialog that returns the user’s text input. When the dialog opens, it displays
the given prompt text and its text edit field is initialized with any specified default text. When
the user clicks OK to dismiss the dialog, it returns the text the user entered. If the user clicks
the Cancel button in this dialog, this method’s result is the value null.
Checkbox
Scrollbar
EditText
Window
Button
Slider
Panel
active x x x x x x x
bounds x x x x x x x x x
children x x x x x x x x x
enabled x x x x x x x x x
jumpdelta x
justify x x x x x x x
32 JavaScript UI Reference Introduction
RadioButton
StaticText
Checkbox
Scrollbar
EditText
Window
Button
Slider
Panel
maxvalue x x
minvalue x x
parent x x x x x x x x x
stepdelta x
text x x x x x x x
textselection x
type x x x x x x x x x
value x x x x
visible x x x x x x x x x
Properties
Following are the properties defined for each element types listed above.
defaultElement -- Object
The element to notify when a user types the Enter key, with the intent to dismiss the dialog as
if the “OK” button had been clicked.
cancelElement -- Object
The element to notify when a user types the Esc key (or the <Cmd .> combination on a Mac),
with the intent to dismiss the dialog as if the “Cancel” button had been clicked.
You can set an element’s bounds property and indirectly create a Bounds object in any of
these ways:
e.bounds = Object
The object must contain properties named left, top, right, bottom, or x, y, width, height, where
each property has an integer coordinate value.
e.bounds = Array
The array must have integer coordinate values in the order [left, top, right, bottom].
e.bounds = String
The string must be an executable JavaScript inline object declaration, containing the same
property names as in the object case just described.
A Bounds object may be accessed as an array. In addition, it supports the following properties
Checkbox
Scrollbar
EditText
Window
Button
Slider
Panel
add() x x
center() x
close() x
hide() x x x x x x x x x
notify() x x x x x x
36 JavaScript UI Reference Introduction
RadioButton
StaticText
Checkbox
Scrollbar
EditText
Window
Button
Slider
Panel
show() x x x x x x x x x
onChange() x x x
onClick() x x x
onClose() x
onMove() x
onResize() x
Methods
Descriptions of the common methods and event handlers listed above follow:
onResize() no return
value This method is called when a Window has
been resized. If you are interested in
processing this event, define a function of
this name in the Window object.
UI Object descriptions
This section describes UI objects such as windows, panels, buttons, checkboxes and so on.
JavaScript Reference Guide JavaScript UI Reference 39
Window object
To create a new Window object:
If you specify a Panel whose width is 0, it will appear as a vertical line; a panel whose height is 0
will appear as a horizontal line. Making a panel invisible will also hide all its children; making it
visible again will also make visible those children that were visible when the panel was made
invisible.
40 JavaScript UI Reference Introduction
The EditText control calls the onChange() event method if the editable text is changed or if its
notify() method is called. It also has a textselection property to access any text selection within the
edit field.
The Button control calls the onClick() event method if the control is clicked or if its notify() method
is called.
The Checkbox control calls the onClick() event method if the control is clicked or if its notify()
method is called. It also has a value property which indicates whether the control is set or not.
All RadioButtons in a group must be created sequentially, with no intervening creation of other
element types. Only one RadioButton in a group can be set at a time; setting a different RadioButton
42 JavaScript UI Reference Introduction
unsets the original one. The RadioButton control calls the onClick() event method if the control is
clicked or if its notify() method is called. It also has a value property which indicates whether the
control is set or not.
The Scrollbar control will have a horizontal orientation if the specified width is greater than its
height at creation time; its orientation will be vertical if its height is greater than its width. It calls
the onChange() event method if the position of the moveable element is changed by the user, or if
its notify() method is called. The value property contains the current position of the scrollbar’s
moveable position indicator within the scrolling area, within the range of minvalue and maxvalue.
All Slider controls have a horizontal orientation. The Slider control calls the onChange() event
method if the position of the slider is changed by the user, or if its notify() method is called. The
value property contains the current position of the slider’s moveable position indicator, within the
range of minvalue and maxvalue.
3
Platform Interface
Different platforms implement different types of file systems. As a result, notations for specifying
files and folders differ dramatically from one file system to the next. File system drives are
organized into folders (or directories) and folders typically contain files or other folders.
File systems are organized hierarchically and each file or folder hasd a position relative to the
“top” of the file system. The complete description of a file’s location in the file system is called
a path.
To create a File or Folder object, use the corresponding File() and Folder() functions. You can also
create them with the new operator if you like; both ways of calling File() or Folder() return a new
object. The constructor accepts full or partial path names. In either case, the path stored internally
is an absolute, full path name, so a File or Folder object, once created, always points to a fixed
location of the disk. If you do not supply a file or folder name, a temporary name is generated.
Path names are in a portable format (see below).
The Folder object supports file system functionality such as walking directories, creating,
renaming or removing files, or resolving file aliases. The File class supports I/O functions to read
or write files. Note that a File or Folder instance does not actually create a File or Folder in the file
system, although each class has a method to accomplish this, if desired.
File and Folder objects can be used at any place where a path name is required; its conversion to a
string (the toString() method) returns the name of the file or folder as an absolute path name in
URI notation (see the absoluteURI property below). If you need the operating system specific file
name, use the fsName property.
43
44 File and Folder Objects JavaScript Reference Guide
When you create two File objects that refer to the same disk file, they are treated as distinct objects.
If you open one of the File objects for I/O, the operating system may inhibit access to the opened
File object from the other File object because the disk file already is open.
There are several methods to distinguish between a File and a Folder object. Here are some
examples:
Path names
There are significant differences among Windows, Macintosh and Unix file systems. The File and
Folder objects provide functionality that allows you to interact with these systems in both
platform-specific and platform-neutral ways.
You can use absolute path names and relative path names. Absolute path names start with one or
two slash characters. These path names describe the full path from a root directory down to a file
or folder. Relative path names start off a known location, the current directory. A relative path
name starts either with a directory name or with one of the special names "." and "..". The name "."
refercs to the current directory, and the name ".." refers to the parent directory. The slash character
is used to separate path elements.
Path Description
/dir1/dir2/file An absolute path name, describing the file file in the directory
dir2, which is in the directory dir1, which again is in the root
directory.
./file The file file in the current directory; you could also simple use
file without the beginning "./" sequence.
../file The file file in the parent of the current directory.
../../file The file file in the grandparent of the current directory.
../dir1/file The file file in the directory dir1, which is parallel to the current
directory.
JavaScript Reference Guide File and Folder Objects 45
When using portable path names, it is always a good idea to use relative path names. Setting the
current directory is as easy as assigning a new path name to the property Folder.current. Relative
path names make you independent of different volume names on different machines and
operating systems.
Internally, the File and Folder objects always operate on the operating system specific path names.
You can always retrieve the "real" path name by looking at the fsName property.
Special characters -- characters that are not alphanumeric and not one of the characters / - - . ! ~ * '
( ) -- are encoded in UTF-8 notation. The file "Däumling" therefore has the portable name
"D%C3%A4umling". Along the same lines, "Macintosh HD" would become "Macintosh%20HD".
This encoding scheme is compatible to RFC 2396 as well as to the global JavaScript functions
encodeURI() and decodeURI().
Volume names
There is no common location in the various file systems where the names of mounted volumes are
stored. On Mac OS X, all mounted volumes are entries in the /Volumes directory. On Unix systems,
there is no convention at all, and Windows does not mount remote volumes at all; there are only
drive letters.
For this reasons, the File and Folder objects support a common convention. A volume name may
be the first part of an absolute path. The objects know where to look for the volume names on the
Macintosh and Windows and they translate the volume names accordingly. On Unix, no
translation takes place.
On some occasions, there may actually be a directory in the root folder that has the same name as
the volume name. Imagine a folder "C:\C" on Windows. Since the File and Folder objects do not
know whether "/c" would address the drive C: or the directory "C:\C", a path name where the
first element designates both a volume name and a directory name always describes the directory
name. If you really need to access the volume by name, you will have to use an operating system
specific path specifier.
All three platforms (Windows, Unix and Mac OS X) provide a definition for a home directory
based on the username of the current user, as illustrated below.
46 File and Folder Objects JavaScript Reference Guide
Note: Windows systems look for the environment variable HOME and use whatever directory is
found there as the home directory. If the HOME environment variable is undefined, the system
uses the user's home directory, typically located in the "Documents and Settings" folder, as the
home directory. In a Windows system, therefore, the following path would equate to the HOME
directory: C:\Documents and Settings\<username>. Also note that on Windows (as well as on
Unix) you can override the default home directory assignment by creating a HOME environment
variable. The path name stored in the HOME environment variable must be a Windows path
name or a UNC path name, not a portable path name.
The following examples assume jdoe as the username, and "~/file" as the file.
Note: Path names may vary depending on the operating system version and language.
The following code is used to reference a file in a script that is stored in the user’s home directory,
regardless of the platform the script is running on.
Depending on the platform, the local path for the file reference (.fsName) would look something
like this:
Mac
/Users/jdoe/custdata.cfg
Windows
C:\Documents and Settings\jdoe\custdata.cfg
Unix
/user/jdoe/custdata.cfg
JavaScript Reference Guide File and Folder Objects 47
Aliases on Windows and the Macintosh work much the same. All accesses to the alias file are
transparently forwarded to the real file behind the alias file. Only the rename() and remove() calls
affect an alias directly.
Windows
Both the slash and the backslash character are valid path element separators. The file system is not
case sensitive.
To access remote volumes, use UNC path names of the form //servername/sharename. These path
names are portable, because both Max OS X and Unix ignore multiple slash characters. Despite the
name (the U in UNC stands for Universal), UNC names do not work for local volumes.
On Windows, all file system aliases (here called shortcuts) are actual files whose name end with
the extension ".lnk". You should never use this extension directly, however. The File and Folder
objects work fine without these extensions. Imagine a shortcut to the file some.txt. The Windows
file name would actually be some.txt.lnk. Use some.txt to create a File object matching this link. The
alias property of this object would return true, and the resolve() method of the object would return
the File object of the actual file. This behavior is the same as on the Macintosh. The ".lnk" extension
for Windows aliases is used transparently; that is, renaming a Windows shortcut file renames the
file name portion and leaves the ".lnk" extension intact.
These behaviors are portable, but please keep in mind that Windows permits a file and its alias to
reside in the same folder. If you have a file "test.txt" and its alias (which is "test.txt.lnk"), and you
48 File and Folder Objects JavaScript Reference Guide
create a File object with "test.txt" you will access the original file and not the alias file. There is no
way for you to access the alias file on a Windows system in this case.
Macintosh
When Mac OS X boots, the boot volume is the root directory of the file system. All other volumes,
including remote volumes, are part of the /Volumes directory. When looking at the first element of
a path name, the File and Folder objects do the following:
Mac OS X path names are not case sensitive, as opposed to all other Unix dialects.
The following examples assume the boot volume to be MacOSX, and a mounted volume Remote.
Mac OS 9 is not longer supported as an operating system. The old notation of path names using
the colon as a path separator, however, is still supported and translates as follows:
Unix
Since the path name conventions are closely modeled after the Unix model, no translation takes
place. For the home directory, the HOME environment variable is used, which is part of any shell
environment. Symbolic links are treated as file system aliases.
Portability issues
If you have to use multiple different machines and operating systems, try to use relative path
names, or try to originate your path names from the home directory. If impossible, work with Mac
OS X and Unix aliases and UNC names on Windows, and store your files on a machine that is
remote to your Windows machine so you can use UNC names.
For example, use the Unix machine gonzo as the data storage. If you set up an alias share in the root
directory of gonzo and if you set up a Samba share at share pointing to the same data location, the
path name //gonzo/share/file would work well for Windows, Macintosh and Unix machines.
Unicode I/O
Usually, the contents of a file are in some 8-bit encoding; most often, the current system encoding
is used, like code page 1252 on Windows or Mac Roman on the Macintosh. When doing file I/O,
the encoding used to convert between 8-bit character sets and Unicode is by default assumed to be
the system encoding. You can, however, set a large number of encodings by setting the encoding
property of a file to the name of the desired encoding. This name is one of the standard Internet
names that are used to describe the encoding of HTML files. Typical examples are ASCII, X-SJIS, or
ISO-8859-1. The File object attempts to find the corresponding encoder in the operating system. If
present, this encoder will be used for subsequent I/O. Reading the encoding property returns the
current encoding.
A special encoder, BINARY, is present for binary I/O. This encoder simply extends every 8-bit
character it finds to a Unicode character between 0 and 255. When using this encoder to write
binary files, the encoder writes the lower 8 bits of the Unicode character. If, for example, the
Unicode character 1000 is written, the encoder actually writes the character 232 (1000 is 0x3E8, and
0xE8 gets written, which is 232).
The data of some of the common file formats (UCS-2, UCS-4, UTF-8, UTF-16) starts with a special
Byte Order Mark (BOM) character ("\uFEFF"). The File method open() reads a few bytes of a file
and tries to detect this character. If successful, the corresponding encoding is set automatically and
the character is skipped. If there is no BOM character at the beginning of the file, open() reads the
first 2 Kbytes of the file and checks whether the data might be valid UTF-8 encoded data, and sets
the encoding to UTF-8 if so.
50 Scriptable properties and methods JavaScript Reference Guide
To write 16-bit Unicode files in UTF-16 format, use the encoding UCS-2. This encoding uses
whatever endian format the host system supports. Make sure to write the Byte Order Mark
character "\uFEFF" as the first character of the file. Do this also when using the UTF-8 encoding.
Error handling
Each object has an error property. If accessing a property or calling a method caused an error, this
property contains a message describing the type of the error. On success, the property contains the
empty string. The property can be set, but setting it only causes the error message to be cleared. If
a file is open, assigning an arbitrary value to the property also resets its error flag.
• Constructors
A constructor is a global function that is used to create the actual objects of a class. It has the
same name as the class of the object that it creates (like File or Folder). When called, it returns
a new instance of the desired object.
• Class methods
These methods are attached to the constructor. They are used for working with objects that the
constructor returns, but they do not require an actual object of that class to work upon. These
methods are also often refereed to as static methods. A typical example is File.openDialog(),
which returns a new File object if the user specifies a file in the Open dialog.
• Object methods
These methods are attached to an instance of an object, because they need a specific object to
act upon. The open() method of a File object is a typical example; in order to work correctly, it
needs the path name of the disk file that the File object actually wraps.
You may also see class properties and object properties referenced in a similar manner. Class
properties provide access to general data related to a class, while object properties provide
access to data specific to an object, like the creation date of a specific file.
To give you some idea of how these distinctions play out in practice, here are some real-world
examples:
// File and Folder constructors are in fact class methods which return
// objects, as illustrated below:
var fRef = new File( "~/myDoc" );
// This code illustrates a Property that returns the name of the current
// operating system
File.fs;
A key point to remember is that class members do not require an instance of the class to be created
in order to access them.
52 Scriptable properties and methods JavaScript Reference Guide
Common elements
Both the File and the Folder objects share a common set of properties and methods. All properties
and methods resolve file system aliases automatically unless indicated otherwise.
Class properties
Class methods
Object properties
created Date The creation date of the object. If the object does not refer to a folder or
file on disk, the value is null. Read-only.
error String Contains a message describing the last file system error. Setting this
value clears any error message and resets the error bit for opened files.
exists Boolean Returns true if the path name of this object refers to an actually existing
file or folder. Read only.
fsName String The file-system specific name of the object as a full path name. Read-
only.
modified Date The date of the object's last modification. If the object does not refer to a
folder or file on disk, the value is null. Read-only.
name String The name of the object without the path specification. Read-only.
parent Folder The folder object containing this object. If this object already is the root
folder of a volume, the property value is null. Read-only.
path String The path portion of the absolute URI. If the name does not have a path,
this property contains the empty string. Read-only.
relativeURI String The path name for the object in URI notation, relative to the current
folder. Read-only.
54 Scriptable properties and methods JavaScript Reference Guide
Object methods
Class properties
Constructor
Folder (path);
new Folder (path);
This function constructs a new Folder object. If the given path name refers to an already
existing disk file, a File object is returned instead.
Class Methods
The following code presents a dialog with which to interactively select a directory/folder. In this
example, the dialog defaults to the local user HOME directory/folder as a starting location for
browsing. The method returns a Folder object reference on success; null on failure.
Object methods
getFiles (String mask); Array Get a list of File and Folder objects contained in the folder
object. The mask is the search mask for the file names. It
may contain question marks and asterisks and is preset to *
to find all files. Alternatively, a function may be supplied.
This function is called with a File or Folder object for every
file or folder in the directory search. If the function returns
true, the object is added to the array.
Constructor
File (path);
new File (path);
This function constructs a new File object. If the given path name refers to an already existing
folder, a Folder object is returned instead. The CRLF sequence is preset to the system default,
and the encoding is preset to the default system encoding.
Class Methods
The following code presents the user with a dialog with which to interactively select a file. The
optional second argument, the form of which differs between Windows and Macintosh, provides a
means to filter the list of files shown in the dialog display list. The point of the example is to show
how to obtain a reference to an existing JavaScript script file. The method returns a Folder object
reference on success; null on failure.
// Windows
if ( Folder.fs == “Windows” ) {
var openFile = File.openDialog( “Select a JavaScriptfile”,
“JavaScript files:*.js” );
} else if ( Folder.fs == “Macintosh” ) {
var openFile = File.openDialog( “Select a JavaScriptfile”, fileFilter );}
return false;
}
The following code sample is similar to the one presented above for openDialog(). However, it is
intended for use in specifying a file save target. Note that a name to a not-already-existing
document can be entered by the user (including extension if desired), but that the dialog does not
create to file, nor does it actually save a file if an existing file is selected. Rather, the reference
60 Scriptable properties and methods JavaScript Reference Guide
returned is used to perform that operation. When used in support of document operations in
Photoshop, for example, that means that using the File object reference with the client’s saveAs()
method, would look something like this:
Object properties
Object methods
close();
Closes the open file. The return value is true if the file was closed, false on I/O errors.
copy (target);
Copies the file to the given location. You can supply an URI path name as well as another File
object. If there is a file at the target location, it is overwritten. The method returns true if the
copy was successful, false otherwise. The method resolves any aliases to find the source file.
The return value is true if the file has been opened successfully, false otherwise.
read (chars);
Read the contents of the file from the current position on. Returns a string that contains up to
the number of characters that were supposed to be read.
readch();
Read one single text character. Line feeds are recognized as CR, LF, CRLF or LFCR pairs. If the
file is encoded, multiple bytes may be read to create single Unicode characters.
readln();
Read one line of text. Line feeds are recognized as CR, LF, CRLF or LFCR pairs. If the file is
encoded, multiple bytes may be read to create single Unicode characters.
tell();
Returns the current position in the file as a an offset in bytes.
Error messages
The following messages may be returned in the error property.
Note, however, that the File object cannot process extended Unicode characters with values
greater than 65535. These characters are left encoded as specified in the UTF-16 standard in as two
characters in the range from 0xD700-0xDFFF.
The ASCII encoder raises errors for characters greater than 127, and the BINARY encoder simply
converts between bytes and Unicode characters by using the lower 8 bits. The latter encoder is
convenient for reading and writing binary data.
Additional encodings
In Windows, all encodings use so-called code pages. These code pages are assigned numeric
values. The usual Western character set that Windows uses is e.g. the code page 1252. Windows
code pages may be selected by prepending the number of the code page with "CP" or
"WINDOWS- like "CP1252" for the code page 1252. The File object has a lot of other encoding
names built-in that match predefined code page numbers. If a code page is not present, the
encoding cannot be selected.
66 Supported encoding names JavaScript Reference Guide
On the Macintosh, encoders may be selected by name rather than by code page number. The File
object queries the Macintosh OS directly for an encoder. As far as Macintosh character sets are
identical with Windows code pages, the Macintosh also knows the Windows code page numbers.
On Unix systems, the number of available encoders depends on the installation of the iconv library.
The following encoding names are implemented both on Windows and Macintosh systems:
UTF-7,UTF7,UNICODE-1-1-UTF-7,X-UNICODE-2-0-UTF-7
ISO-8859-2,ISO-8859-2,ISO-8859-2:1987,ISO-IR-101,LATIN2
ISO-8859-3,ISO-8859-3,ISO-8859-3:1988,ISO-IR-109,LATIN3
ISO-8859-4,ISO-8859-4,ISO-8859-4:1988,ISO-IR-110,LATIN4,BALTIC
ISO-8859-5,ISO-8859-5,ISO-8859-5:1988,ISO-IR-144,CYRILLIC
ISO-8859-6,ISO-8859-6,ISO-8859-6:1987,ISO-IR-127,ECMA-114,ASMO-708,ARABIC
ISO-8859-7,ISO-8859-7,ISO-8859-7:1987,ISO-IR-126,ECMA-118,ELOT-928,GREEK8,GREEK
ISO-8859-8,ISO-8859-8,ISO-8859-8:1988,ISO-IR-138,HEBREW
ISO-8859-9,ISO-8859-9,ISO-8859-9:1989,ISO-IR-148,LATIN5,TURKISH
ISO-8859-10,ISO-8859-10,ISO-8859-10:1992,ISO-IR-157,LATIN6
ISO-8859-13,ISO-8859-13,ISO-IR-179,LATIN7
ISO-8859-14,ISO-8859-14,ISO-8859-14,ISO-8859-14:1998,ISO-IR-199,LATIN8
ISO-8859-15,ISO-8859-15,ISO-8859-15:1998,ISO-IR-203
ISO-8859-16,ISO-885,ISO-885,MS-EE
CP850,WINDOWS-850,IBM850
CP866,WINDOWS-866,IBM866
CP932,WINDOWS-932,SJIS,SHIFT-JIS,X-SJIS,X-MS-SJIS,MS-SJIS,MS-KANJI
CP936,WINDOWS-936,GBK,WINDOWS-936,GB2312,GB-2312-80,ISO-IR-58,CHINESE
CP949,WINDOWS-949,UHC,KSC-5601,KS-C-5601-1987,KS-C-5601-1989,ISO-IR-149,KOREAN
CP950,WINDOWS-950,BIG5,BIG-5,BIG-FIVE,BIGFIVE,CN-BIG5,X-X-BIG5
CP1251,WINDOWS-1251,MS-CYRL
CP1252,WINDOWS-1252,MS-ANSI
CP1253,WINDOWS-1253,MS-GREEK
CP1254,WINDOWS-1254,MS-TURK
CP1255,WINDOWS-1255,MS-HEBR
CP1256,WINDOWS-1256,MS-ARAB
CP1257,WINDOWS-1257,WINBALTRIM
CP1258,WINDOWS-1258
CP1361,WINDOWS-1361,JOHAB
EUC-JP,EUCJP,X-EUC-JP
EUC-KR,EUCKR,X-EUC-KR
HZ,HZ-GB-2312
X-MAC-JAPANESE
X-MAC-GREEK
X-MAC-CYRILLIC
X-MAC-LATIN
X-MAC-ICELANDIC
X-MAC-TURKISH
JavaScript Reference Guide Supported encoding names 67
CP437,IBM850,WINDOWS-437
CP709,WINDOWS-709,ASMO-449,BCONV4
EBCDIC
KOI-8R
KOI-8U
ISO-2022-JP
ISO-2022-KR
These names are alias names for encodings that the Macintosh operating system might know.
TIS-620,TIS620,TIS620-0,TIS620.2529-1,TIS620.2533-0,TIS620.2533-1,ISO-IR-166
CP874,WINDOWS-874
JP,JIS-C6220-1969-RO,ISO646-JP,ISO-IR-14
JIS-X0201,JISX0201-1976,X0201
JIS-X0208,JIS-X0208-1983,JIS-X0208-1990,JIS0208,X0208,ISO-IR-87
JIS-X0212,JIS-X0212.1990-0,JIS-X0212-1990,X0212,ISO-IR-159
CN,GB-1988-80,ISO646-CN,ISO-IR-57
ISO-IR-16,CN-GB-ISOIR165
KSC-5601,KS-C-5601-1987,KS-C-5601-1989,ISO-IR-149
EUC-CN,EUCCN,GB2312,CN-GB
EUC-TW,EUCTW,X-EUC-TW
Unix encodings
On Unix systems, the File object looks for the presence of the iconv library, and it uses whatever
encoding it finds there. If you, therefore, need a special encoding on a Unix system, make sure that
there is an iconv encoding module installed that converts between UTF-16 (the internal format that
the File object uses) and the desired encoding.
68 Supported encoding names JavaScript Reference Guide
4
JavaScript Debugging
This section describes the information and controls of the JavaScript Debugger window, as
illustrated below.
debug output
view
JavaScript
source view
breakpoints display
69
70 The Debugger Window JavaScript Reference Guide
All debugging output appears in the upper-right pane of the JavaScript Debugger window.
Specifically, output from the print method of the “$” object appears in this debug output view.
The currently executing JavaScript source appears in the lower pane of the JavaScript Debugger
window. Double-clicking a line in this JavaScript source view sets or clears an unconditional
breakpoint on that line. That is, if a breakpoint is in effect for that line, double-clicking it clears the
breakpoint, and vice-versa. The line number column to the left of the source view displays a red
dot for all lines with a breakpoint.
Resume
Ctrl-R (Windows)
Resumes execution of the script with the JavaScript Debugger window open. When the script
terminates, the application closes the JavaScript Debugger window automatically. Closing the
debugger window manually also causes script execution to resume. This button is enabled when
script execution is paused or stopped.
Pause
Ctrl-P (Windows)
Halts the currently executing script temporarily and reactivate the JavaScript Debugger window.
This button is enabled when a script is running.
JavaScript Reference Guide The Debugger Window 71
Stop
Ctrl-K (Windows)
Stops execution of the script and generate a runtime error. This button is enabled when a script is
running.
Step Over
Ctrl-S (Windows)
Halts after executing a single JavaScript statement in the script; if the statement calls a JavaScript
function, execute the function in its entirety before stopping.
Step Into
Ctrl-T (Windows)
Halts after executing a single JavaScript statement in the script or after executing a single
statement in any JavaScript function that the script calls.
Step Out
Ctrl-U (Windows)
When the debugger is paused within the body of a JavaScript function, clicking this button
resumes script execution until the function returns. When paused outside the body of a function,
clicking this button resumes script execution until the script terminates.
Clicking this button displays the Script Breakpoints Window. Type in a line number that
corresponds to a desired breakpoint and a condition about whether to stop or not. For more
information on breakpoints, see “JavaScript Breakpoints Window” on page 75.
72 The Debugger Window JavaScript Reference Guide
Enter in this field a JavaScript statement to execute within the stack scope of the line highlighted in
the Stack Trace view. When you’ve finished entering the JavaScript expression, you can execute it
by clicking the command line entry button or pressing the Enter key. Click the button next to the
field or press Enter to execute the JavaScript code in the command line entry field. The application
executes the contents of the command line entry field within the stack scope of the line
highlighted in the Stack Trace view.
The command line entry field accepts any JavaScript code, making it very convenient to use for
inspecting or changing the contents of variables.
Note: To list the contents of an object as if it were JavaScript source code, enter the
object.toSource() command, replacing object with the object that you want to display.
Setting Breakpoints
You can set breakpoints in the debugger itself, by calling methods of the $ object, or by defining
them in your JavaScript code.
function setupBox(box) {
// break unconditionally at the next line
debugger;
box.width = 48;
box.height = 48;
box.url = "none";
}
To execute a breakpoint in runtime code, call the $.bp() method, as shown in the following
example:
function setupBox(box) {
box.width = (box.width == undefined) ? $.bp() : 48;
box.height = (box.height == undefined) ? $.bp() : 48;
box.url = (box.url == undefined) ? $.bp() : "none";
}
This example breaks if any of the width, height, or url attributes of the custom element are
undefined. Of course, you wouldn’t put bp method calls into commercial code—it’s more
appropriate for shipping code to set default values for undefined properties, as the previous
example does. Again, debugging must be enabled; if not, the system ignores the $.bp() method.
function setupBox(box) {
box.width = 48; $.bp (box.width == undefined);
box.height = 48; $.bp (box.height == undefined);
box.url = "none"; $.bp (box.url == undefined);
}
Provided that $.level is set to a value greater than zero, the debugger will become activated and
stop on a line containing this statement. This property effectively functions as a breakpoint
statement. See “The Debugger Object ($)” on page 77 for more information.
74 The Debugger Window JavaScript Reference Guide
Script Prompt
When a run-time error is encountered while debugging a script, the following dialog is typically
displayed.
• If Yes is selected, the error is ignored and script processing attempts to continue on the next
executable line
• If No is selected, the error is handled as it would be during normal (non-debug) execution
• If the error was encountered in a script-defined try block, execution jumps to the first line of
the try’s associated catch block
• If the error was not encountered in a script-defined try block, script execution is terminated
immediately
Note: To debug through the normal flow of execution in such try block circumstances, users
typically select No. However, if the error is determined not to be of a nature that would
compromise continued in-line execution (such as during script development), you are given
the option of not having to terminate, fix or restart.
JavaScript Reference Guide The Debugger Window 75
This dialog displays all defined breakpoints. This dialog does not display:
Breakpoints set in this window persist across multiple executions of a script. When the application
quits, or a script is reloaded, it removes all breakpoints.
activates. The breakpoint also activates if there is a syntax or runtime error during the
execution of the condition.
• Click “New” to change the line number of the breakpoint, to add or remove a breakpoint
condition, or to create a new breakpoint.
JavaScript Reference Guide The Debugger Object ($) 77
Properties
Property Type Description
error Error Retrieves the last runtime error. Reading this property returns an Error object
containing information about the last runtime error.
level Number Sets the debugging level. This may be one of three values:
0 – disable debugging.
1 – break on runtime errors.
2 – break at the beginning of the script.
Note that the debugger statement is disabled as well if the debugging level is
0. Also, your scripting environment needs to support level 2 explicitly. If level
2 does not work, use the statement "$.level = 1; debugger;" at the beginning
of your script.
version String Returns the version number of the engine as a three-part number like "3.1.11".
Read only.
os String Outputs the current operating system version. Read only.
Debug output
write (text, …);
writeln (text, …);
Writes the given string to the Debug Output window. The writeln method appends a New
Line character to its arguments.
Breakpoints
setbp (scriptletName, line, [condition]);
Sets a breakpoint. The breakpoint is defined by the name of the scriptlet or function and the
line number. If the name is the empty string or missing, the name of the currently executing
scriptlet is used. If the line number is zero or not supplied, the current line number is used.
Thus, the call $.setbp() without parameters sets a breakpoint at the current position.
Optionally, a condition may be supplied. This is a JavaScript expression string that is
evaluated before the breakpoint is executed. The breakpoint is only executed if the expression
returns true.
The special string "NEXTCALL", as the scriptlet name suggests, causes the engine to execute a
breakpoint the next time a function call is executed.
bp([condition]);
Executes a breakpoint at the current position. Optionally, a condition may be supplied. This is
a JavaScript expression string that is evaluated before the breakpoint is executed. The
breakpoint is only executed if the expression returns true. If no condition is given, the use of
the debugger statement is recommended.
Other methods
gc()
Initiates garbage collection. Garbage collection is a convenience function that automatically
collects all varibles declared as var. This method allow you to manually invoke garbage
collection.
Returns: Undefined
80 The Debugger Object ($) JavaScript Reference Guide
5
Utilities
Photoshop actions are different from scripts. A Photoshop action is a series of tasks you have
recorded while using the application—menu choices, tool choices, selection, and other commands.
When you “play” an action, Photoshop performs all of the recorded commands.
Actions and scripts are two ways of automating repetitive tasks, but they work very differently.
• You cannot add conditional logic to an action. Unlike a script, actions cannot make decisions
based on the current situation.
• A single script can target multiple hosts. Actions can’t. For example, you could target both
Photoshop and Illustrator in the same script.
The Actions palette, invoked under the Window menu, supports actions with a great deal of
sophistication (including the ability to display dialogs) and allows users to work with selected
objects, as illustrated below.
The action manager is a Photoshop CS utility that helps you manage and manipulate actions when
writing JavaScripts.
81
82 JavaScript Reference Guide
The classes “ActionDescriptor”, “ActionReference” and “ActionList” are all part of the Action
Manager functionality.
When you write scripts that use the Action Manager, you should install the “ScriptingListener”
plug-in. This plug-in is located in the “Scripting Guide” folder. Look inside the “utilities” folder
that is part of the scripting support download.
“ScriptingListener” records most of your actions to a file on your hard drive. To avoid slowing
down Photoshop as well as not to create a big file on your drive, only install the plug-in when you
are creating Action Manager scripts.
When “ScriptingListener” is installed it will record a file with scripting code corresponding to the
actions that you perform from the UI.
• ScriptingListenerJS.log: the file is created on the desktop and contains JavaScript code
corresponding to the actions that are performed from the UI.
Note: There is no AppleScript interface to the Action Manager, but you can execute JavaScripts
from AppleScript, so you are able to access Action Manager functionality from AppleScripts.
When the ScriptingListener is installed, running the Emboss filter is recorded to a file called
“ScriptingListenerJS.log” (see above for location of this file on the various platforms).
Open the “ScriptingListenerJS.log” file. At the end of the file you will see something like the
following. Note the numbers may vary:
The ScriptingListener divides every command by a line, so it is easy to find the last command.
The next step in making Emboss scriptable is to identify the values that you entered (135, 3 and
100). Copy the JavaScript code from the “ScriptingListenerJS.log” file to another file and substitute
the filter values with variable names. In the following example, we have wrapped the code in a
JavaScript function and replaced 135 with angle, 3 with height, and 100 with amount.
You now have a JavaScript function that performs the Emboss filter on the current document. To
activate the Emboss filter from JavaScript you must include the function definition shown above
and then call the function with the desired parameters. To apply Emboss with angle 75, height 2
and amount 89, you say:
You need to re-write your JavaScript code slightly to work with the “do javascript” command to
use the “arguments” collection to get access to the AppleScript values from JavaScript. For
example change the Emboss JavaScript shown in the previous section to the following and save it
in a file called “Emboss.js”:
To access JavaScript code from VBScript, you must use the “DoJavaScriptFile” command and
provide specific settings in the “arguments” parameter.
From VBScript you can then run the Emboss filter by saying:
The object classes of the JavaScript type library are presented alphabetically and in tabular format
in this interface section.
• Properties of a class include the property itself, access status (read only or read/write) ,
value type, and a description.
When the value type is an enumeration, enumerated values are defined in UPPER CASE, as
illustrated below:
Note: Descriptions are omitted for properties and methods that are self-explanatory; for example:
removeAll. Return values and parameter types, if none apply, may also be left blank.
Sample code for several object model classes is given to help illustrate the syntax as well as usage
of the object class.
87
88 ActionDescriptor JavaScript Reference Guide
ActionDescriptor
Properties
Property Access Value Type What it is
count RO Long number of keys contained in the
descriptor
Methods
Method What it does Parameter Type Returns
clear Clears the descriptor
erase Erases a key from the Key as Long
descriptor
getBoolean Gets the value of a key Key as Long Boolean
of type boolean
getClass Gets the value of a key Key as Long Long
of type class
getDouble Gets the value of a key Key as Long Double
of type double
getEnumerationType Gets the enumeration Key as Long Long
type of a key
getEnumerationValue Gets the enumeration Key as Long Long
value of a key
getInteger Gets the value of a key Key as Long Long
of type integer
getKey Gets ID of the Nth key Index as Long Long
getList Gets the value of a key Key as Long ActionList
of type list
getObjectType Gets the class ID of an Key as Long Long
object in a key of type
object
getObjectValue Gets the value of a key Key as Long ActionDescriptor
of type object
getPath Gets the value of a key Key as Long File
of type Alias
getReference Gets the value of a key Key as Long ActionReference
of type
ActionReference
JavaScript Reference Guide ActionDescriptor 89
ActionList
Properties
Property Access Value Type What it is
count RO Long number of items in the list
Methods
Method What it does Parameter Type Returns
clear Clear the list
getBoolean Gets the value of an Index as Long Boolean
item of type boolean
getClass Gets the value of an Index as Long Long
item of type class
getDouble Gets the value of an Index as Long Double
item of type double
getEnumerationType Gets the enumeration Index as Long Long
type of an item
getEnumerationValue Gets the enumeration Index as Long Long
value of an item
getInteger Gets the value of an Index as Long Long
item of type integer
getList Gets the value of an Index as Long ActionList
item of type list
getObjectType Gets the class ID of an Index as Long Long
object in an item of
type object
getObjectValue Gets the value of an Index as Long ActionDescriptor
item of type object
getPath Gets the value of an Index as Long File
item of type Alias
getReference Gets the value of an Index as Long ActionReference
item of type
ActionReference
getString Gets the value of an Index as Long String
item of type string
getType Gets the type of an Index as Long DescValueType
item
JavaScript Reference Guide ActionList 91
ActionReference
Methods
Method What it does Parameter Type Returns
getContainer ActionReference
getDesiredClass Long
getEnumeratedType Gets type of Long
enumeration of an
ActionReference
whose form is
'Enumerated'
getEnumeratedValue Gets value of Long
enumeration of an
ActionReference
whose form is
'Enumerated'
getForm Gets form of ReferenceFormType
ActionReference
getIdentifier Gets identifier value for Long
an ActionReference
whoxse form is
'Identifier'
getIndex Gets index value for an Long
ActionReference
whoxse form is 'Index'
getName Gets name value for an String
ActionReference
whoxse form is 'Name'
getOffset Gets offset value for an Long
ActionReference
whoxse form is 'Offset'
getProperty Gets property ID value Long
for an ActionReference
whoxse form is
'Property'
putClass desiredClass as Long
putEnumerated desiredClass as Long
enumType as Long
Value as Long
putIdentifier desiredClass as Long
Value as Long
JavaScript Reference Guide ActionReference 93
Application
Properties
Property Access Value Type What it is
activeDocument R/W Document the frontmost document
backgroundColor R/W SolidColor
colorSettings R/W ANYTHING name of selected color settings' set
displayDialogs R/W DialogModes controls whether or not Photoshop
DialogModes.ALL displays dialogs
DialogModes.ERROR
DialogModes.NO
documents RO Documents the open documents
fonts RO TextFonts the fonts installed on this system
foregroundColor R/W SolidColor
freeMemory RO Double the amount of unused memory available
to Adobe Photoshop
name RO String the application's name
path RO File the full path of the location of the
Photoshop application
preferences RO Preferences preference settings
scriptingVersion RO String the version of the Scripting interface
version RO String the version of Adobe Photoshop
application
Methods
Method What it does Parameter Type Returns
beep
charIDToTypeID Converts from a four charID as String Long
character code to a
runtime ID
doAction Plays an action from action as String
the Actions Palette from as String
JavaScript Reference Guide Application 95
Pressing the OK button on the alert box opens a second dialog, which asks users whether they
would like the foreground and background colors set for the document presently open. If no
document is open, the script opens a new document for the user.
96 Application JavaScript Reference Guide
The script (with no document open) produces the following progression of dialogs.
Code (application.js)
// answer will be true for a “Yes” answer and false for a “No” answer
var answer = confirm(“Do you want me to set the foreground and background to my
favorite colors?”);
// I don’t have a favorite color. Why did I ask you may wonder?
app.foregroundColor.rgb.red = Math.random() * 255;
app.foregroundColor.rgb.green = Math.random() * 255;
app.foregroundColor.rgb.blue = Math.random() * 255;
// use the application’s path and the offset to the samples folder
var sampleDocToOpen = File(app.path + “/Samples/Eagle.psd”);
The script produces the following progression of images as a PDF slide show.
Code (PDFPresentation.js)
// get all the files found in this folder that are Photoshop (.psd)
var inputFiles = inputFolder.getFiles(“*.psd”);
options.view = true;
options.autoAdvance = true;
options.interval = 5;
options.loop = true;
options.transition = TransitionType.RANDOM;
Note: To run this code on non-English platforms, substitue the following path for the outputFile
variable:
ArtLayer
Properties
Property Access Value Type What it is
allLocked R/W Boolean
blendMode R/W BlendMode
BlendMode.COLORBLEND
BlendMode.COLORBURN
BlendMode.COLORDODGE
BlendMode.DARKEN
BlendMode.DIFFERENCE
BlendMode.DISSOLVE
BlendMode.EXCLUSION
BlendMode.HARDLIGHT
BlendMode.HUE
BlendMode.LIGHTEN
BlendMode.LINEARBURN
BlendMode.LINEARDODGE
BlendMode.LINEARLIGHT
BlendMode.LUMINOSITY
BlendMode.MULTIPLY
BlendMode.NORMAL
BlendMode.OVERLAY
BlendMode.PASSTHROUGH
BlendMode.PINLIGHT
BlendMode.SATURATION
BlendMode.SCREEN
BlendMode.SOFTLIGHT
BlendMode.VIVIDLIGHT
bounds RO Array( UnitValue ) Bounding rectangle of the
Layer
fillOpacity R/W Double the interior opacity of the
layer (between 0.0 and
100.0)
grouped R/W Boolean is the layer grouped with
the layer below?
Photoshop CS changed the
menu name to Create/
Release Clipping Mask
isBackgroundLayer R/W Boolean is the layer a background
layer?
JavaScript Reference Guide ArtLayer 101
Methods
Method What it does Parameter Type Returns
adjustBrightnessContrast Adjusts brightness as Long
brightness and contrast as Long
contrast
adjustColorBalance shadows as Object
midtones as Object
highlights as Object
preserveLuminosity as Boolean
adjustCurves Adjusts curves curveShape as Object
of the selected
channels
adjustLevels Adjusts levels inputRangeStart as Long
of the selected inputRangeEnd as Long
channels inputRangeGamma as Double
outputRangeStart as Long
outputRangeEnd as Long
applyAddNoise Applies the add amount as Double
noise filter
distribution as NoiseDistribution
NoiseDistribution.GAUSSIAN
NoiseDistribution.UNIFORM
monochromatic as Boolean
applyBlur Applies the blur
filter
applyBlurMore Applies the blur
more filter
applyClouds Applies the
clouds filter
applyCustomFilter Applies the characteristics as Object
custom filter scale as Long
offset as Long
applyDeInterlace Applies the De- eliminateFields as EliminateFields
Interlace filter EliminateFields.EVENFIELDS
EliminateFields.ODDFIELDS
createFields as CreateFields
CreateFields.DUPLICATION
CreateFields.INTERPOLATION
applyDespeckle Applies the
despeckle filter
JavaScript Reference Guide ArtLayer 103
undefinedAreass as UndefinedAreas
UndefinedAreas.REPEATEDGEPIXELS
UndefinedAreas.WRAPAROUND
displacementMapFile as File
applyDustAndScratches Applies the radius as Long
dust and threshold as Long
scratches filter
applyGaussianBlur Applies the radius as Double
Gaussian blur
filter
applyGlassEffect Applies the distortion as Long
glass filter smoothness as Long
scaling as Long
invert as Boolean
texture as TextureType
TextureType.BLOCKS
TextureType.CANVAS
TextureType.FILE
TextureType.FROSTED
TextureType.TINYLENS
textureFile as File
applyHighPass Applies the radius as Double
high pass filter
104 ArtLayer JavaScript Reference Guide
lensType as LensType
LensType.MOVIEPRIME
LensType.PRIME105
LensType.PRIME35
LensType.ZOOMLENS
applyMaximum Applies the radius as Double
maximum filter
applyMedianNoise Applies the radius as Double
median noise
filter
applyMinimum Applies the radius as Double
minimum filter
applyMotionBlur Applies the angle as Long
motion blur radius as Double
filter
applyNTSC Applies the
NTSC colors
filter
applyOceanRipple Applies the size as Long
ocean ripple magnitude as Long
filter
applyOffset Applies the horizontal as UnitValue
offset filter vertical as UnitValue
undefinedAreas as OffsetUndefinedAreas
OffsetUndefinedAreas.REPEATEDGEPIXELS
OffsetUndefinedAreas.SETTOBACKGROUND
OffsetUndefinedAreas.WRAPAROUND
applyPinch Applies the amount as Long
pinch filter
applyPolarCoordinates Applies the conversion as PolarConversionType
polar PolarConversionType.POLARTORECTANGULAR
coordinates PolarConversionType.RECTANGULARTOPOLAR
filter
JavaScript Reference Guide ArtLayer 105
blurQuality as RadialBlurQuality
RadialBlurQuality.BEST
RadialBlurQuality.DRAFT
RadialBlurQuality.GOOD
applyRipple Applies the amount as Long
ripple filter
size as RippleSize
RippleSize.LARGE
RippleSize.MEDIUM
RippleSize.SMALL
applySharpen Applies the
sharpen filter
applySharpenEdges Applies the
sharpen edges
filter
applySharpenMore Applies the
sharpen more
filter
applyShear Applies the curve as Object
shear filter
undefinedAreas as UndefinedAreas
UndefinedAreas.REPEATEDGEPIXELS
UndefinedAreas.WRAPAROUND
applySmartBlur Applies the radius as Double
smart blur filter threshold as Double
blurQuality as SmartBlurQuality
SmartBlurQuality.HIGH
SmartBlurQuality.LOW
SmartBlurQuality.MEDIUM
mode as SmartBlurMode
SmartBlurMode.EDGEONLY
SmartBlurMode.NORMAL
SmartBlurMode.OVERLAYEDGE
106 ArtLayer JavaScript Reference Guide
waveType as WaveType
WaveType.SINE
WaveType.SQUARE
WaveType.TRIANGULAR
undefinedAreas as UndefinedAreas
UndefinedAreas.REPEATEDGEPIXELS
UndefinedAreas.WRAPAROUND
randomSeed as Long
applyZigZag Applies the amount as Long
zigzag filter ridges as Long
style as ZigZagType
ZigZagType.AROUNDCENTER
ZigZagType.OUTFROMCENTER
ZigZagType.PONDRIPPLES
autoContrast Adjusts
contrast of the
selected
channels
automatically
JavaScript Reference Guide ArtLayer 107
anchor as AnchorPosition
AnchorPosition.BOTTOMCENTER
.AnchorPosition.BOTTOMLEFT
AnchorPosition.BOTTOMRIGHT
AnchorPosition.MIDDLECENTER
AnchorPosition.MIDDLELEFT
AnchorPosition.MIDDLERIGHT
AnchorPosition.TOPCENTER
AnchorPosition.TOPLEFT
AnchorPosition.TOPRIGHT
rotate angle as Double
]
anchor as AnchorPosition
AnchorPosition.BOTTOMCENTER
.AnchorPosition.BOTTOMLEFT
AnchorPosition.BOTTOMRIGHT
AnchorPosition.MIDDLECENTER
AnchorPosition.MIDDLELEFT
AnchorPosition.MIDDLERIGHT
AnchorPosition.TOPCENTER
AnchorPosition.TOPLEFT
AnchorPosition.TOPRIGHT
JavaScript Reference Guide ArtLayer 109
Sample Script
The following script creates art layers to display a duck and a sand dune in an overlying
checkerboard pattern. An alert box prompts the user to press OK. A multi-layered collage then
displays.
Code (ArtLayer.js)
// use the document name for the layer name in the merged document
var docName = app.activeDocument.name;
ArtLayers
Properties
Property Access Value Type What it is
length RO Long number of elements in the collection
parent RO Object the object's container
Methods
Method What it does Parameter Type Returns
add Creates a new object ArtLayer
getByName Get the first element in name as String ArtLayer
the collection with the
provided name
removeAll
114 BitmapConversionOptions JavaScript Reference Guide
BitmapConversionOptions
Properties
Property Access Value Type What it is
angle R/W Double only valid for 'halftone screen'
conversions
frequency R/W Double only valid for 'halftone screen'
conversions
method R/W BitmapConversionType.CUSTOMPATTERN ( default: BitmapConversionType
BitmapConversionType.DIFFUIONDITHER BitmapConversionType.-->
BitmapConversionType.HALFTHRESHOLD DIFFUSIONDITHER )
BitmapConversionType.HALFTONESCREEN
BitmapConversionType.PATTERNDITHER
patternName R/W only valid for 'custom pattern' conversions String
resolution R/W output resolution (in pixels per inch) Double
shape R/W only valid for 'halftone screen' conversions BitmapHalfToneType
JavaScript Reference Guide BMPSaveOptions 115
BMPSaveOptions
Properties
Property Access Value Type What it is
alphaChannels R/W Boolean save alpha channels
depth R/W BMPDepthType number of bits per sample
BMPDepthType.BMP_A1R5G5B5
BMPDepthType.BMP_A4R4G4B4
BMPDepthType.BMP_A8R8G8B8
BMPDepthType.BMP_R5G6B5
BMPDepthType.BMP_R8G8B8
BMPDepthType.BMP_X1R5G5B5
BMPDepthType.BMP_X4R4G4B4
BMPDepthType.BMP_X8R8G8B8
BMPDepthType.EIGHT
BMPDepthType.FOUR
BMPDepthType.ONE
BMPDepthType.SIXTEEN
BMPDepthType.THIRTYTWO
BMPDepthType.TWENTYFOUR
flipRowOrder R/W Boolean
osType R/W OperatingSystem target OS. Windows or OS/2 ( default:
OperatingSystem.OS2 OperatingSystem.WINDOWS )
OperatingSystem.WINDOWS
rleCompression R/W Boolean should RLE compression be used?
116 Channel JavaScript Reference Guide
Channel
Properties
Property Access Value Type What it is
color R/W SolidColor color of the channel (not valid for
component channels)
histogram RO Object color of the channel (not valid for
component channels)
kind R/W ChannelType type of the channel
ChannelType.COMPONENT
ChannelType.MASKEDAREA
ChannelType.SELECTEDAREA
ChannelType.SPOTCOLOR
name R/W String the channel's name
opacity R/W Double opacity of alpha channels (called solidity
for spot channels)
parent RO Object the object's container
visible R/W Boolean
Methods
Method What it does Parameter Type Returns
duplicate Duplicates the targetDocument as Document Channel
channel
merge Merges a spot channel
into the component
channels
remove Deletes the object
JavaScript Reference Guide Channels 117
Channels
Properties
Property Access Value Type What it is
length RO Long number of elements in the collection
parent RO Object the object’s container
Methods
Method What it does Parameter Type Returns
add Creates a new object Channel
getByName Get the first element in name as String Channel
the collection with the
provided name
removeAll
Sample Script
The following script produces a strobe effect, as a progression of dialogs display.
118 Channels JavaScript Reference Guide
Code (Histogram.js)
// channel indexer
var channelIndex = 0;
if (docRef.mode == DocumentMode.RGB ||
docRef.mode == DocumentMode.INDEXEDCOLOR ||
docRef.mode == DocumentMode.CMYK) {
// loop through all the items and output in the following format
// 001 XXXXX
// 002 XX
for (histogramIndex = 0; histogramIndex < inHistogram.length;
histogramIndex++) {
// I need an extra “0” for this line item to keep everything in line
if (histogramIndex < 10)
inOutFile.write(“0”);
// I need an extra “0” for this line item to keep everything in line
if (histogramIndex < 100)
inOutFile.write(“0”);
inOutFile.write(“\n”);
}
inOutFile.write(“\n”);
}
case DocumentMode.BITMAP:
case DocumentMode.GRAYSCALE:
case DocumentMode.INDEXEDCOLOR:
visibleChannelCount = 1;
break;
case DocumentMode.DUOTONE:
visibleChannelCount = 2;
break;
case DocumentMode.RGB:
case DocumentMode.LAB:
visibleChannelCount = 3;
break;
case DocumentMode.CMYK:
visibleChannelCount = 4;
break;
case DocumentMode.DUOTONE:
visibleChannelCount = 4;
break;
case DocumentMode.MULTICHANNEL:
default:
visibleChannelCount = inDocument.channels.length + 1;
122 Channels JavaScript Reference Guide
break;
}
}
JavaScript Reference Guide CMYKColor 123
CMYKColor
Properties
Property Access Value Type What it is
black R/W Double the black color value (between 0.0 and
100.0)
cyan R/W Double the black color value (between 0.0 and
100.0)
magenta R/W Double the magenta color value (between 0.0 and
100.0)
yellow R/W Double the yellow color value (between 0.0 and
100.0)
124 DCS1_SaveOptions JavaScript Reference Guide
DCS1_SaveOptions
Properties
Property Access Value Type What it is
dCS R/W DCSType ( default:
DCSType.COLORCOMPOSITE DCSType.COLORCOMPOSITE )
DCSType.GRAYSCALECOMPOSITE
DCSType.NOCOMPOSITE
embedColorProfil R/W Boolean embed color profile in document
e
encoding R/W SaveEncoding type of encoding to use for
SaveEncoding.ASCII document ( default:
SaveEncoding.BINARY SaveEncoding.BINARY )
SaveEncoding.JPEGHIGH
SaveEncoding.JPEGLOW
SaveEncoding.JPEGMAXIMUM
SaveEncoding.JPEGMEDIUM
halftoneScreen R/W Boolean include halftone screen ( default:
false )
interpolation R/W Boolean use image interpolation ( default:
false )
preview R/W Preview type of preview ( default:
Preview.EIGHTBITTIFF Preview.MACOSEIGHTBIT )
Preview.MACOSEIGHTBIT
Preview.MACOSJPEG
Preview.MACOSMONOCHROME
Preview.MONOCHROMETIFF
Preview.NONE
transferFunction R/W Boolean include transfer functions in
document ( default: false )
vectorData R/W Boolean include vector data
JavaScript Reference Guide DCS2_SaveOptions 125
DCS2_SaveOptions
Properties
Property Access Value Type What it is
dCS R/W DCSType ( default: DCSType.NOCOMPOSITE )
DCSType.COLORCOMPOSITE
DCSType.GRAYSCALECOMPOSITE
DCSType.NOCOMPOSITE
embedColorProfile R/W Boolean embed color profile in document
encoding R/W SaveEncoding type of encoding to use for
SaveEncoding.ASCII document ( default:
SaveEncoding.BINARY SaveEncoding.BINARY )
SaveEncoding.JPEGHIGH
SaveEncoding.JPEGLOW
SaveEncoding.JPEGMAXIMUM
SaveEncoding.JPEGMEDIUM
halftoneScreen R/W Boolean include halftone screen ( default:
false )
interpolation R/W Boolean use image interpolation ( default:
false )
multiFileDCS R/W Boolean ( default: false )
preview R/W Preview type of preview ( default:
Preview.EIGHTBITTIFF Preview.MACOSEIGHTBIT )
Preview.MACOSEIGHTBIT
Preview.MACOSJPEG
Preview.MACOSMONOCHROME
Preview.MONOCHROMETIFF
Preview.NONE
spotColors R/W Boolean save spot colors
transferFunction R/W Boolean include transfer functions in
document ( default: false )
vectorData R/W Boolean include vector data
126 Document JavaScript Reference Guide
Document
Properties
Property Access Value Type What it is
activeChannels R/W Object selected channels for
document
activeHistoryBrushSource R/W HistoryState the current history state to
use with the history brush for
this document
activeHistoryState R/W HistoryState the current history state for
this document
activeLayer R/W Object (Layer) selected layer for document
artLayers RO ArtLayers the top level art layers in this
document
backgroundLayer RO ArtLayer background layer for the
document. Only valid for
documents that have a
background layer
bitsPerChannel R/W BitsPerChannelType number of bits per channel
BitsPerChannelType.EIGHT
BitsPerChannelType.ONE
BitsPerChannelType.SIXTEEN
channels RO Channels the channels in this
document
colorProfileName R/W String name of color profile for
document. Only valid for
documents that have been
assigned a color profile
colorProfileType R/W ColorProfile type of color profile
ColorProfile.CUSTOM management for document
ColorProfile.NONE
ColorProfile.WORKING
componentChannels RO Object all color component channels
for this document
fullName RO File full path name of document
height RO UnitValue height of document (unit
value)
histogram RO Object a histogram of values for the
composite document (only
for RGB, CMYK and 'Indexed
colors' documents)
JavaScript Reference Guide Document 127
Methods
Method What it does Parameter Type Returns
changeMode Changes the mode of destinationMode as ChangeMode
the document ChangeMode.BITMAP
ChangeMode.CMYK
ChangeMode.GRAYSCALE
ChangeMode.INDEXEDCOLOR
ChangeMode.LAB
ChangeMode.MULTICHANNEL
ChangeMode.RGB
options as Object
(DocumentConversionOptions)
close Closes the document saving as SaveOptions
SaveOptions.DONOTSAVECHANGES
SaveOptions.PROMPTTOSAVECHANGES
SaveOptions.SAVECHANGES
convertProfile Convert sthe destinationProfile as String
document from using intent as Intent
one color profile to Intent.ABSOLUTECOLORIMETRIC
using an other Intent.PERCEPTUAL
Intent.RELATIVECOLORIMETRIC
Intent.SATURATION
blackPointCompensation as Boolean
dither as Boolean
Dither.DIFFUSION
Dither.NOISE
Dither.NONE
Dither.PATTERN
crop Crops the document bounds as Array( UnitValue )
angle as Double
width as UnitValue
height as UnitValue
duplicate Creates a duplicate of Document
the object
exportDocument exportIn as File
exportAs as ExportType
ExportType.ILLUSTRATORPATHS
options as ExportOptionsIllustrator
flatten Flattens all layers in the
document
JavaScript Reference Guide Document 129
sourceSpace as SourceSpaceType
SourceSpaceType.DOCUMENT
SourceSpaceType.PROOF
printSpace as String
intent as Intent
Intent.ABSOLUTECOLORIMETRIC
Intent.PERCEPTUAL
Intent.RELATIVECOLORIMETRIC
Intent.SATURATION
blackPointCompensation as Boolean
rasterizeAllLayers Rasterizes all layers
resizeCanvas Changes the size of the width as UnitValue
canvas height as UnitValue
anchor as AnchorPosition
AnchorPosition.BOTTOMCENTER
.AnchorPosition.BOTTOMLEFT
AnchorPosition.BOTTOMRIGHT
AnchorPosition.MIDDLECENTER
AnchorPosition.MIDDLELEFT
AnchorPosition.MIDDLERIGHT
AnchorPosition.TOPCENTER
AnchorPosition.TOPLEFT
AnchorPosition.TOPRIGHT
130 Document JavaScript Reference Guide
resampleMethod as ResampleMethod
ResampleMethod.BICUBIC
ResampleMethod.BICUBICSHARPER
ResampleMethod.BICUBICSMOOTHER
ResampleMethod.BILINEAR
ResampleMethod.NEARESTNEIGHBOR
ResampleMethod.NONE
revealAll Expands document to
show clipped sections
rotateCanvas Rotates canvas of angle as Double
document
save Saves the document
saveAs Saves the document saveIn as File
with specific save options as ANYTHING
options asCopy as Boolean
extensionType as Extension
Extension.LOWERCASE
Extension.NONE
Extension.UPPERCASE
splitChannels Splits channels of the Object
document
trap Applies trap to a CMYK width as Long
document
trim type as TrimType
TrimType.BOTTOMRIGHT
TrimType.TOPLEFT
TrimType.TRANSPARENT
top as Boolean
left as Boolean
bottom as Boolean
right as Boolean
JavaScript Reference Guide Document 131
Sample Script
The following script creates a document that contains two images (an eagle and a duck) obtained
from the Photoshop samples folder.
First, a test is made to determine which image is larger. Then the smaller image is resized to match
the larger image. A merged document twice as high as either image is subsequently created in
order to hold the two images, one stacked on top of the other.
A selection is made on the upper part of the document to paste in the eagle. The selection process
is then inverted and the duck is pasted into the lower part of the document. In the final display, the
eagle is positioned over the duck.
Code (Document.js)
app.activeDocument = mergedDoc;
mergedDoc.selection.select(selRegion);
// inverting the selection we made before gets us the bottom of the document
mergedDoc.selection.invert();
JavaScript Reference Guide Document 133
DocumentInfo
Properties
Property Access Value Type What it is
author R/W String
authorPosition R/W String
caption R/W String
captionWriter R/W String
category R/W String
city R/W String
copyrighted R/W CopyrightedType
CopyrightedType.COPYRIGHTEDWORK
CopyrightedType.PUBLICDOMAIN
CopyrightedType.UNMARKED
copyrightNotice R/W String
country R/W String
creationDate R/W String
credit R/W String
exif read Object An array of 2 element
onlly arrays of type string
(key/value pairs)
headline R/W String
instructions R/W String
jobName R/W String
keywords R/W Object list of keywords
ownerUrl R/W String
parent RO Object the object's container
Sample Script
The following script opens a pop-up that allows you to select a file.
Code (DocumentInfo.js)
// save the output’s in JPEG with quality really low for small files
var jpegOptions = new JPEGSaveOptions();
Documents
Properties
Property Access Value Type What it is
length RO Long number of elements in the collection
parent RO Object the object's container
Methods
Method What it does Parameter Type Returns
add Adds a document width as UnitValue Document
height as UnitValue
resolution as Double
name as String
mode as NewDocumentMode
NewDocumentMode.BITMAP
NewDocumentMode.CMYK
NewDocumentMode.GRAYSCALE
NewDocumentMode.LAB
NewDocumentMode.RGB
initialFill as DocumentFill
DocumentFill.BACKGROUNDCOLOR
DocumentFill.TRANSPARENT
DocumentFill.WHITE
pixelAspectRatio as Double
getByName Get the first element in name as String Document
the collection with the
provided name
JavaScript Reference Guide EPSOpenOptions 139
EPSOpenOptions
Properties
Property Access Value Type What it is
antiAlias R/W Boolean use antialias?
constrainProportions R/W Boolean constrain proportions of image
height R/W UnitValue height of image (unit value)
mode R/W OpenDocumentMode the document mode
OpenDocumentMode.CMYK
OpenDocumentMode.GRAYSC
OpenDocumentMode.ALE
OpenDocumentMode.LAB
OpenDocumentMode.RGB
resolution R/W Double the resolution of the document (in
pixels per inch)
width R/W UnitValue width of image (unit value)
140 EPSSaveOptions JavaScript Reference Guide
EPSSaveOptions
Properties
Property Access Value Type What it is
embedColorProfile R/W Boolean embed color profile in document
encoding R/W SaveEncodingSaveEncoding.ASCII type of encoding to use for
SaveEncoding.BINARY document ( default:
SaveEncoding.JPEGHIGH SaveEncoding.BINARY )
SaveEncoding.JPEGLOW
SaveEncoding.JPEGMAXIMUM
SaveEncoding.JPEGMEDIUM
halftoneScreen R/W Boolean include halftone screen ( default:
false )
interpolation R/W Boolean use image interpolation ( default:
false )
preview R/W Preview type of preview
Preview.EIGHTBITTIFF
Preview.MACOSEIGHTBIT
Preview.MACOSJPEG
Preview.MACOSMONOCHROME
Preview.MONOCHROMETIFF
Preview.NONE
psColorManagement R/W Boolean use Postscript color management (
default: false )
transferFunction R/W Boolean include transfer functions in
document
( default: false )
transparentWhites R/W Boolean only valid when saving BitMap
documents
vectorData R/W Boolean include vector data
JavaScript Reference Guide ExportOptionsIllustrator 141
ExportOptionsIllustrator
Properties
Property Access Value Type What it is
path R/W IllustratorPathType which path to export ( default:
IllustratorPathType.ALLPATHS IllustratorPathType.DOCUMENTBOUNDS )
IllustratorPathType.DOCUMENTBOUNDS
IllustratorPathType.NAMEDPATH
pathName R/W String name of path to export. Only valid if
you are exporting a named path
142 GalleryBannerOptions JavaScript Reference Guide
GalleryBannerOptions
Properties
Property Access Value Type What it is
contactInfo R/W String web photo gallery contact info
date R/W String web photo gallery date
font R/W GalleryFontType the font setting for the banner text
GalleryFontType.ARIAL ( default: GalleryFontType.ARIAL )
GalleryFontType.COURIERNEW
GalleryFontType.HELVETICA
GalleryFontType.TIMESNEWROMAN
fontSize R/W Long the size of the font for the banner
text ( 1 - 7; default: 3 )
photographer R/W String web photo gallery photographer (
default: )
siteName R/W String web photo gallery site name (
default: Adobe Web Photo Gallery )
JavaScript Reference Guide GalleryCustomColorOptions 143
GalleryCustomColorOptions
Properties
Property Access Value Type What it is
activeLinkColor R/W RGBColor active link color
backgroundColor R/W RGBColor background color
bannerColor R/W RGBColor banner color
linkColor R/W RGBColor link color
textColor R/W RGBColor text color
visitedLinkColor R/W RGBColor visited link color
144 GalleryImagesOptions JavaScript Reference Guide
GalleryImagesOptions
Properties
Property Access Value Type What it is
border R/W Long the amount of border pixels
you want between your
images ( 0 - 99; default: 0 )
caption R/W Boolean generate a caption for the
images ( default: false )
dimension R/W Long resized image dimensions in
pixels ( default: 350 )
font R/W GalleryFontType font for the gallery images text
GalleryFontType.ARIAL ( default:
GalleryFontType.COURIERNEW GalleryFontType.ARIAL )
GalleryFontType.HELVETICA
GalleryFontType.TIMESNEWROMAN
fontSize R/W Long font size for the gallery images
text ( 1 - 7; default: 3 )
imageQuality R/W Long the quality setting for the JPEG
image ( 0 - 12; default: 5 )
includeCopyright R/W Boolean include the copyright in the
text for the gallery images (
default: false )
includeCredits R/W Boolean include the credits in the text
for the gallery images ( default:
false )
includeFilename R/W Boolean include the file name in the
text for the gallery images (
default: true )
includeTitle R/W Boolean include the title in the text for
the gallery images ( default:
false )
numericLinks R/W Boolean add numeric links ( default:
true )
resizeConstraint R/W GalleryConstrainType how should the image be
GalleryConstrainType.CONSTRAINBOTH constrained ( default:
GalleryConstrainType.CONSTRAINHEIGHT GalleryConstrainType.CONSTR
GalleryConstrainType.CONSTRAINWIDTH AINBOTH )
resizeImages R/W Boolean resize images data ( default:
true )
JavaScript Reference Guide GalleryOptions 145
GalleryOptions
Properties
Property Access Value Type What it is
addSizeAttributes R/W Boolean add width and height attributes for
images ( default: true )
bannerOptions R/W GalleryBannerOptions options related to banner settings
customColorOptions R/W GalleryCustomColorOptions options related to custom color settings
emailAddress R/W String the email address to show on the web
page ( default: )
imagesOptions R/W GalleryImagesOptions options related to images settings
includeSubFolders R/W Boolean include all files found in sub folders of
the input folder ( default: true )
layoutStyle R/W String the style to use for laying out the web
page ( default: Centered Frame 1 - Basic )
preserveAllMetadata R/W Boolean save all of the metadata in the JPEG files
( default: false )
securityOptions R/W GallerySecurityOptions options related to security settings
thumbnailOptions R/W GalleryThumbnailOptions options related to thumbnail settings
useShortExtension R/W Boolean short web page extension .htm or long
web page extension .html ( default: true
)
useUTF8Encoding R/W Boolean web page should use UTF-8 encoding (
default: false )
146 GallerySecurityOptions JavaScript Reference Guide
GallerySecurityOptions
Properties
Acce
Property Value Type What it is
ss
content R/W GallerySecurityType web photo gallery
GallerySecurityType.CAPTION security content (
GallerySecurityType.COPYRIGHT default:
GallerySecurityType.CREDIT GallerySecurityType.NO
GallerySecurityType.CUSTOMTEXT NE )
GallerySecurityType.FILENAME
GallerySecurityType.NONE
GallerySecurityType.TITLE
font R/W GalleryFontType web photo gallery
GalleryFontType.ARIAL security font ( default:
GalleryFontType.COURIERNEW GalleryFontType.ARIAL
GalleryFontType.HELVETICA )
GalleryFontType.TIMESNEWROMAN
fontSize R/W Long web photo gallery
security font size ( 1 -
72; default: 3 )
opacity R/W Long web page security
opacity as a percent (
default: 100 )
text R/W String web photo gallery
security custom text
textColor R/W RGBColor web page security text
color
textPosition R/W GallerySecurityTextPositionType web photo gallery
GallerySecurityTextPositionType.CENTERED security text position (
GallerySecurityTextPositionType.LOWERLEFT default:
GallerySecurityTextPositionType.LOWERRIGHT GallerySecurityTextPosi
GallerySecurityTextPositionType.UPPERLEFT tionType.CENTERED )
GallerySecurityTextPositionType.UPPERRIGHT
textRotate R/W GallerySecurityTextRotateType web photo gallery
GallerySecurityTextRotateType.CLOCKWISE45 security text rotate (
GallerySecurityTextRotateType.CLOCKWISE90 default:
GallerySecurityTextRotateType.COUNTERCLOCKWISE45 GallerySecurityTextRot
GallerySecurityTextRotateType.COUNTERCLOCKWISE90 ateType.ZERO )
GallerySecurityTextRotateType.ZERO
JavaScript Reference Guide GalleryThumbnailOptions 147
GalleryThumbnailOptions
Properties
Property Access Value Type What it is
border R/W Long the amount of border pixels you
want around your thumbnail
images ( 0 - 99; default: 0 )
caption R/W Boolean with caption ( default: false )
columnCount R/W Long web photo gallery thumbnail
columns ( default: 5 )
dimension R/W Long web photo gallery thumbnail
dimension in pixels ( default: 75 )
font R/W GalleryFontType web photo gallery font ( default:
GalleryFontType.ARIAL GalleryFontType.ARIAL )
GalleryFontType.COURIERNEW
GalleryFontType.HELVETICA
GalleryFontType.TIMESNEWROMAN
fontSize R/W Long the size of the font for the
thumbnail images text ( 1 - 7;
default: 3 )
includeCopyright R/W Boolean include copyright for thumbnail (
default: false )
includeCredits R/W Boolean include credits for thumbnail (
default: false )
includeFilename R/W Boolean include file name for thumbnail (
default: false )
includeTitle R/W Boolean include title for thumbnail ( default:
false )
rowCount R/W Long web photo gallery thumbnail rows (
default: 3 )
size R/W GalleryThumbSizeType the size of the thumbnail images (
GalleryThumbSizeType.CUSTOM default:
GalleryThumbSizeType.LARGE GalleryThumbSizeType.MEDIUM )
GalleryThumbSizeType.MEDIUM
GalleryThumbSizeType.SMALL
148 GIFSaveOptions JavaScript Reference Guide
GIFSaveOptions
Properties
Property Access Value Type What it is
colors R/W Long number of colors in palette (only
settable for some palette types)
dither R/W Dither type of dither
Dither.DIFFUSION
Dither.NOISE
Dither.NONE
Dither.PATTERN
ditherAmount R/W Long amount of dither. Only valid for
diffusion ( 1 - 100; default: 75 )
forced R/W ForcedColors
ForcedColors.BLACKWHITE
ForcedColors.NONE
ForcedColors.PRIMARIES
ForcedColors.WEB
interlaced R/W Boolean should rows be interlaced? ( default:
false )
matte R/W MatteType
MatteType.BACKGROUND
MatteType.BLACK
MatteType.FOREGROUND
MatteType.NETSCAPENONE
MatteType.SEMIGRAY
MatteType.WHITE
palette R/W Palette ( default: Palette.LOCALSELECTIVE )
Palette.EXACT
Palette.LOCALADAPTIVE
Palette.LOCALPERCEPTUAL
Palette.LOCALSELECTIVE
Palette.MACOSPALETTE
Palette.MASTERADAPTIVE
Palette.MASTERPERCEPTUAL
Palette.MASTERSELECTIVE
Palette.PREVIOUSPALETTE
Palette.UNIFORM
Palette.WEBPALETTE
Palette.WINDOWSPALETTE
preserveExactColors R/W Boolean
transparency Boolean
JavaScript Reference Guide GrayColor 149
GrayColor
Properties
Property Access Value Type What it is
gray R/W Double the gray value ( 0.0 - 100.0; default: 0.0 )
150 HistoryState JavaScript Reference Guide
HistoryState
Properties
Property Access Value Type What it is
name RO String the channel's name
parent RO Object the object's container
snapshot RO Boolean is the history state a snapshot?
JavaScript Reference Guide HistoryStates 151
HistoryStates
Properties
Property Access Value Type What it is
length RO Long number of elements in the collection
parent RO Object the object's container
Methods
Method What it does Parameter Type Returns
getByName Get the first element in name as String HistoryState
the collection with the
provided name
152 HSBColor JavaScript Reference Guide
HSBColor
Properties
Property Access Value Type What it is
brightness R/W Double the brightness value (between 0.0 and
100.0)
hue R/W Double the hue value (between 0.0 and 360.0)
saturation R/W Double the saturation value (between 0.0 and
100.0)
JavaScript Reference Guide IndexedConversionOptions 153
IndexedConversionOptions
Properties
Property Access Value Type What it is
colors R/W Long number of colors in palette (only
settable for some palette types)
dither R/W Dither type of dither
Dither.DIFFUSION
Dither.NOISE
Dither.NONE
Dither.PATTERN
ditherAmount R/W Long amount of dither. Only valid for
diffusion ( 1 - 100 )
forced R/W ForcedColors
ForcedColors.BLACKWHITE
ForcedColors.NONE
ForcedColors.PRIMARIES
ForcedColors.WEB
matte R/W MatteType
MatteType.BACKGROUND
MatteType.BLACK
MatteType.FOREGROUND
MatteType.NETSCAPENONE
MatteType.SEMIGRAY
MatteType.WHITE
palette R/W Palette Type of palette ( default:
Palette.EXACT Palette.EXACT )
Palette.LOCALADAPTIVE
Palette.LOCALPERCEPTUAL
Palette.LOCALSELECTIVE
Palette.MACOSPALETTE
Palette.MASTERADAPTIVE
Palette.MASTERPERCEPTUAL
Palette.MASTERSELECTIVE
Palette.PREVIOUSPALETTE
Palette.UNIFORM
Palette.WEBPALETTE
Palette.WINDOWSPALETTE
preserveExactColors R/W Boolean
transparency R/W Boolean
154 JPEGSaveOptions JavaScript Reference Guide
JPEGSaveOptions
Properties
Property Access Value Type What it is
embedColorProfile R/W Boolean embed color profile in
document
formatOptions R/W FormatOptions ( default:
FormatOptions.OPTIMIZEDBSELINE FormatOptions.STANDARDBA
FormatOptions.PROGRESSIVE SELINE )
FormatOptions.STANDARDBASELINE
matte R/W MatteType
MatteType.BACKGROUND
MatteType.BLACK
MatteType.FOREGROUND
MatteType.NETSCAPENONE
MatteType.SEMIGRAY
MatteType.WHITE
quality R/W Long quality of produced image ( 0 -
12; default: 3 )
scans R/W Long number of scans. Only valid for
progressive type JPEG files ( 3 -
5)
JavaScript Reference Guide LabColor 155
LabColor
Properties
Property Access Value Type What it is
a R/W Double the a-value (between -128.0 and 127.0)
b R/W Double the b-value (between -128.0 and 127.0)
l R/W Double the L-value (between 0.0 and 100.0)
156 LayerComp JavaScript Reference Guide
LayerComp
Properties
Property Access Value Type What it is
appearance R/W Boolean use layer appearance
comment R/W ANYTHING the description of the layer comp
name R/W String the name of the layer comp
parent RO Object the object's container
position R/W Boolean use layer position
selected RO Boolean the layer comp is currently selected
visibility R/W Boolean use layer visibility
Methods
Method What it does Parameter Type Returns
apply Applies the layer comp
to the document
recapture Recaptures the current
layer state(s) for this
layer comp
remove Deletes the object
resetFromComp Resets the layer comp
state to the document
state
JavaScript Reference Guide LayerComps 157
LayerComps
Properties
Property Access Value Type What it is
length RO Long number of elements in the collection
parent RO Object the object's container
Methods
Method What it does Parameter Type Returns
add a layer comp name as String LayerComp
comment as String
appearance as Boolean
position as Boolean
visibility as Boolean
getByName Get the first element in name as String LayerComp
the collection with the
provided name
removeAll
158 Layers JavaScript Reference Guide
Layers
Properties
Property Access Value Type What it is
length RO Long number of elements in the collection
parent RO Object the object's container
Methods
Method What it does Parameter Type Returns
getByName Get the first element in name as String Layer
the collection with the
provided name
removeAll
JavaScript Reference Guide LayerSet 159
LayerSet
Properties
Property Access Value Type What it is
allLocked R/W Boolean
artLayers RO ArtLayers the art layers in this layer set
blendMode R/W BlendMode
BlendMode.COLORBLEND
BlendMode.COLORBURN
BlendMode.COLORDODGE
BlendMode.DARKEN
BlendMode.DIFFERENCE
BlendMode.DISSOLVE
BlendMode.EXCLUSION
BlendMode.HARDLIGHT
BlendMode.HUE
BlendMode.LIGHTEN
BlendMode.LINEARBURN
BlendMode.LINEARDODGE
BlendMode.LINEARLIGHT
BlendMode.LUMINOSITY
BlendMode.MULTIPLY
BlendMode.NORMAL
BlendMode.OVERLAY
BlendMode.PASSTHROUGH
BlendMode.PINLIGHT
BlendMode.SATURATION
BlendMode.SCREEN
BlendMode.SOFTLIGHT
BlendMode.VIVIDLIGHT
bounds RO Array( UnitValue ) Bounding rectangle of the Layer
enabledChannels R/W Object channels that are enabled for the layer set.
Must be a list of component channels
layers RO Layers the layers in this layer set
layerSets RO LayerSets LayerSets contained within a LayerSet
linkedLayers RO Object
name R/W String the name of the layer
opacity R/W Double master opacity of layer ( 0.0 - 100.0 )
parent RO Object the object's container
visible R/W Boolean
160 LayerSet JavaScript Reference Guide
Methods
Method What it does Parameter Type Returns
duplicate Creates a duplicate of relativeObject as Object Object (Layer)
the object insertionLocation as ElementPlacement
ElementPlacement.INSIDE
ElementPlacement.PLACEATBEGINNING
ElementPlacement.PLACEATEND
ElementPlacement.PLACEBEFORE
ElementPlacement.PLACEAFTER
link Links the layer with with as Object (Layer)
another layer
merge Merges the layerset. ArtLayer
Returns a reference to
the art layer that is
created by this method
move Moves the object relativeObject as Object
insertionLocation as ElementPlacement
ElementPlacement.INSIDE
ElementPlacement.PLACEATBEGINNING
ElementPlacement.PLACEATEND
ElementPlacement.PLACEBEFORE
ElementPlacement.PLACEAFTER
remove Deletes the object
LayerSets
Properties
Property Access Value Type What it is
length RO Long number of elements in the collection
parent RO Object the object's container
Methods
Method What it does Parameter Type Returns
add Creates a new object LayerSet
getByName Get the first element in name as String LayerSet
the collection with the
provided name
removeAll Removes the layer set
and any contained
layers or layer sets
Code (LayerSets.js)
$.level = 1;
// an indexer
var i = 0;
myLayerSets[i][0] = docRef.layerSets.add();
}
PathItem
Properties
Property Access Value Type What it is
kind R/W PathKind
PathKind.CLIPPINGPATH
PathKind.NORMALPATH
PathKind.WORKPATH
name
parent RO PathKind the object's container
PathKind.CLIPPINGPATH
PathKind.NORMALPATH
PathKind.WORKPATH
subPathItems RO SubPathItems sub items for this path item
Methods
Method What it does Parameter Type Returns
remove Deletes this path
duplicate Duplicates this path name as String
with a new name
JavaScript Reference Guide PathItem 165
opacity as Double
preserveTransparency as Boolean
feather as Double
wholePath as Boolean
antiAlias as Boolean
antiAlias.CRISP
antiAlias.NONE
antiAlias.SHARP
antiAlias.SMOOTH
antiAlias.STRONG
makeClippingPath Makes this path item flatness as Double
the clipping path for
this document
166 PathItem JavaScript Reference Guide
operation as SelectionType
SelectionType.DIMINISH
SelectionType.EXTEND
SelectionType.INTERSECT
SelectionType.REPLACE
strokePath Strokes the path with tool as ToolType
the following ToolType.ARTHISTORYBRUSH
information ToolType.BACKGROUNDERASER
ToolType.BLUR
ToolType.BRUSH
ToolType.BURN
ToolType.CLONESTAMP
ToolType.COLORREPLACEMENTTOOL
ToolType.DODGE
ToolType.ERASER
ToolType.HEALINGBRUSH
ToolType.HISTORYBRUSH
ToolType.PATTERNSTAMP
ToolType.PENCIL
ToolType.SHARPEN
ToolType.SMUDGE
ToolType.SPONGE
simulatePressure as Boolean
JavaScript Reference Guide PathItem 167
Sample Script
The following script manipulates multiple art paths to produce a multi-colored version of “Hello
World”.
Code (ArtPaths.js)
letterLocationX += letterBoxWidth.value;
AddLetterLPath(letterSubPaths, letterLocationX, letterLocationY,
letterWidth.value, letterHeight.value);
letterLocationX += letterBoxWidth.value;
AddLetterLPath(letterSubPaths, letterLocationX, letterLocationY,
letterWidth.value, letterHeight.value);
letterLocationX += letterBoxWidth.value;
AddLetterOPath(letterSubPaths, letterLocationX, letterLocationY,
letterWidth.value, letterHeight.value);
letterLocationX += letterBoxWidth.value;
AddLetterOPath(letterSubPaths, letterLocationX, letterLocationY,
letterWidth.value, letterHeight.value);
letterLocationX += letterBoxWidth.value;
AddLetterRPath(letterSubPaths, letterLocationX, letterLocationY,
letterWidth.value, letterHeight.value);
letterLocationX += letterBoxWidth.value;
JavaScript Reference Guide PathItem 169
letterLocationX += letterBoxWidth.value;
AddLetterDPath(letterSubPaths, letterLocationX, letterLocationY,
letterWidth.value, letterHeight.value);
// deselect it
myPathItem.deselect();
letterPoints[0].kind = PointKind.CORNERPOINT;
letterPoints[0].anchor = Array(inX + inWidth / 2, inY);
letterPoints[0].leftDirection = letterPoints[0].anchor;
letterPoints[0].rightDirection = letterPoints[0].anchor;
letterPoints[1].kind = PointKind.CORNERPOINT;
letterPoints[1].anchor = Array(inX, inY + inHeight);
letterPoints[1].leftDirection = letterPoints[1].anchor;
letterPoints[1].rightDirection = letterPoints[1].anchor;
insertIndex = inOutSubPaths.length;
inOutSubPaths[insertIndex].operation = ShapeOperation.SHAPEXOR;
inOutSubPaths[insertIndex].closed = false;
inOutSubPaths[insertIndex].entireSubPath = letterPoints;
insertIndex = inOutSubPaths.length;
insertIndex = inOutSubPaths.length;
PathItems
Properties
Property Access Value Type What it is
length RO Long number of elements in the collection
parent RO Object the object's container
Methods
Method What it does Parameter Type Returns
add Creates a new path name as String PathItem
item entirePath as Object
getByName Get the first element in name as String PathItem
the collection with the
provided name
removeAll
178 PathPoint JavaScript Reference Guide
PathPoint
Properties
Property Access Value Type What it is
anchor R/W Array( UnitValue ) the edit point on the curve --
leftDirection/rightDirection are points
representing the control handle end
points
kind R/W PointKind
PointKind.CORNERPOINT
PointKind.SMOOTHPOINT
leftDirection R/W Array( UnitValue )
parent RO Object the object's container
rightDirection R/W Array( UnitValue )
JavaScript Reference Guide PathPointInfo 179
PathPointInfo
Properties
Property Access Value Type What it is
anchor R/W ANYTHING the position of the anchor (in coordinates)
kind R/W PointKind the point type, smooth/conner
PointKind.CORNERPOINT
PointKind.SMOOTHPOINT
leftDirection R/W ANYTHING location of the left direction point (in
position)
rightDirection R/W ANYTHING location of the left direction point (out
position)
180 PathPoints JavaScript Reference Guide
PathPoints
Properties
Property Access Value Type What it is
length RO Long number of elements in the collection
parent RO Object the object's container
JavaScript Reference Guide PDFOpenOptions 181
PDFOpenOptions
Properties
Property Access Value Type What it is
antiAlias R/W Boolean use antialias?
constrainProportions R/W Boolean constrain proportions of image
height R/W UnitValue height of image (unit value)
mode R/W OpenDocumentMode the document mode
OpenDocumentMode.CMYK
OpenDocumentMode.GRAYSC
OpenDocumentMode.ALE
OpenDocumentMode.LAB
OpenDocumentMode.RGB
page R/W Long number of page to open
resolution R/W Double the resolution of the document (in
pixels per inch)
width R/W UnitValue width of image (unit value)
182 PDFSaveOptions JavaScript Reference Guide
PDFSaveOptions
Properties
Property Access Value Type What it is
alphaChannels R/W Boolean save alpha channels
annotations R/W Boolean save annotations
downgradeColorProfile R/W Boolean should the embedded color profile be
downgraded to version 2
embedColorProfile R/W Boolean embed color profile in document
embedFonts R/W Boolean embed fonts? Only valid if vector data is
included
encoding R/W PDFEncoding ( default: PDFEncoding.PDFZIP )
PDFEncoding.JPEG
PDFEncoding.PDFZIP
interpolation R/W Boolean use image interpolation?
jpegQuality R/W Long quality of produced image. Only valid for
JPEG encoded PDF documents ( 0 - 12 )
layers R/W Boolean save layers
spotColors R/W Boolean save spot colors
transparency R/W Boolean
useOutlines R/W Boolean use outlines for text? Only valid if vector
data is included
vectorData R/W Boolean include vector data
JavaScript Reference Guide PhotoCDOpenOptions 183
PhotoCDOpenOptions
Properties
Property Access Value Type What it is
colorProfileName R/W String profile to use when reading the image
colorSpace R/W PhotoCDColorSpace colorspace for image
PhotoCDColorSpace.LAB16
PhotoCDColorSpace.LAB8
PhotoCDColorSpace.RGB16
PhotoCDColorSpace.RGB8
orientation R/W Orientation
Orientation.LANDSCAPE
Orientation.PORTRAIT
pixelSize R/W PhotoCDSize dimensions of image
PhotoCDSize.EXTRALARGE
PhotoCDSize.LARGE
PhotoCDSize.MAXIMUM
PhotoCDSize.MEDIUM
PhotoCDSize.MINIMUM
PhotoCDSize.SMALL
resolution R/W Double the resolution of the image (in pixels per
inch)
184 PhotoshopSaveOptions JavaScript Reference Guide
PhotoshopSaveOptions
Properties
Property Access Value Type What it is
alphaChannels R/W Boolean save alpha channels
annotations R/W Boolean save annotations
embedColorProfile R/W Boolean embed color profile in document
layers R/W Boolean save layers
spotColors R/W Boolean save spot colors
JavaScript Reference Guide PICTFileSaveOptions 185
PICTFileSaveOptions
Properties
Property Access Value Type What it is
alphaChannels R/W Boolean save alpha channels
compression R/W PICTCompression ( default:
PICTCompression.JPEGHIGHPICT PICTCompression.NONE )
PICTCompression.JPEGLOWPICT
PICTCompression.JPEGMAXIMUMPICT
PICTCompression.JPEGMEDIUMPICT
PICTCompression.NONE
embedColorProfile R/W Boolean embed color profile in
document
resolution R/W PICTBitsPerPixels number of bits per pixel
PICTBitsPerPixels.EIGHT
PICTBitsPerPixels.FOUR
PICTBitsPerPixels.SIXTEEN
PICTBitsPerPixels.THIRTYTWO
PICTBitsPerPixels.TWO
186 PICTResourceSaveOptions JavaScript Reference Guide
PICTResourceSaveOptions
Properties
Property Access Value Type What it is
alphaChannels R/W Boolean save alpha channels
compression R/W PICTCompression ( default:
PICTCompression.JPEGHIGHPICT PICTCompression.NONE )
PICTCompression.JPEGLOWPICT
PICTCompression.JPEGMAXIMUMPICT
PICTCompression.JPEGMEDIUMPICT
PICTCompression.NONE
embedColorProfile R/W Boolean embed color profile in
document
name R/W String name of PICT resource (
default: \"\" )
resolution R/W PICTBitsPerPixels number of bits per pixel
PICTBitsPerPixels.EIGHT
PICTBitsPerPixels.FOUR
PICTBitsPerPixels.SIXTEEN
PICTBitsPerPixels.THIRTYTWO
PICTBitsPerPixels.TWO
resourceID R/W PICTBitsPerPixels ID of PICT resource ( default:
PICTBitsPerPixels.EIGHT 128 )
PICTBitsPerPixels.FOUR
PICTBitsPerPixels.SIXTEEN
PICTBitsPerPixels.THIRTYTWO
PICTBitsPerPixels.TWO
JavaScript Reference Guide PixarSaveOptions 187
PixarSaveOptions
Properties
Property Access Value Type What it is
alphaChannels R/W Boolean save alpha channels
188 PNGSaveOptions JavaScript Reference Guide
PNGSaveOptions
Properties
Property Access Value Type What it is
interlaced R/W Boolean should rows be interlaced? ( default: false )
JavaScript Reference Guide Preferences 189
Preferences
Properties
Property Access Value Type What it is
additionalPluginFolder R/W File
appendExtension R/W SaveBehavior on
SaveBehavior.ALWAYSSAVE Windows,
SaveBehavior.ASKWHENSAVING files are
SaveBehavior.NEVERSAVE always
saved with
extensions.
askBeforeSavingLayeredTIFF R/W Boolean
autoUpdateOpenDocuments R/W Boolean
beepWhenDone R/W Boolean
colorChannelsInColor R/W Boolean
colorPicker R/W ColorPicker
ColorPicker.ADOBE
ColorPicker.APPLE
ColorPicker.PLUGIN
ColorPicker.WINDOWS
columnGutter R/W Double gutter of
columns
(in points)
columnWidth R/W Double width of
columns
(in points)
createFirstSnapshot R/W Boolean automatica
lly make
first
snapshot
when a
new
document
is created?
dynamicColorSliders R/W Boolean
editLogItems R/W EditLogItemsType options for
EditLogItemsType.CONCISE edit log
EditLogItemsType.DETAILED items
EditLogItemsType.SESSIONONLY
exportClipboard R/W Boolean
fullSizePreview R/W Boolean Mac only
190 Preferences JavaScript Reference Guide
PresentationOptions
Properties
Property Access Value Type What it is
autoAdvance R/W Boolean auto advance when viewing ( default: true )
downgradeColorProfile R/W Boolean should the embedded color profile be
downgraded to version 2 ( default: false )
embedFonts R/W Boolean embed fonts? Only valid if a text layer is
included ( default: false )
encoding R/W PDFEncoding ( default: PDFEncoding.PDFZIP )
interpolation R/W Boolean use image interpolation? ( default: false )
interval R/W Long time in seconds before auto advancing the
view ( default: 5 )
jpegQuality R/W Long quality of produced image. Only valid for
JPEG encoded PDF documents ( 0 12;
default: 10 )
loop R/W Boolean loop after last page ( default: false )
presentation R/W Boolean true if the file type is presentation false for
Multi-Page document ( default: false )
transition R/W TransitionType transition type when switching to the next
document ( default: Transition-Type.NONE )
transparency R/W Boolean ( default: true )
vectorData R/W Boolean include vector data ( default: false )
view R/W Boolean view the document after saving ( default:
false )
194 RawFormatOpenOptions JavaScript Reference Guide
RawFormatOpenOptions
Properties
Property Access Value Type What it is
bitsPerChannel R/W Long number of bits for each channel (8 or 16)
byteOrder R/W Byte Order only relevant for images with 16 bits per
channel
channelNumber R/W Long number of channels in image
headerSize R/W Long
height R/W Long height of image (in pixels)
interleaveChannels R/W Boolean are the channels in the image interleaved?
retainHeader R/W Boolean retain header when saving?
width R/W Long width of image (in pixels)
JavaScript Reference Guide RawSaveOptions 195
RawSaveOptions
Properties
Property Access Value Type What it is
alphaChannels R/W Boolean save alpha channels
spotColors R/W Boolean save spot colors
196 RGBColor JavaScript Reference Guide
RGBColor
Properties
Property Access Value Type What it is
blue R/W Double the blue color value ( 0.0 - 255.0; default:
255.0 )
green R/W Double the green color value ( 0.0 - 255.0; default:
255.0 )
hexValue R/W String Hex representation of this color
red R/W Double Hex representation of this color
JavaScript Reference Guide Selection 197
Selection
Properties
Property Access Value Type What it is
parent RO Object the object's container
Methods
Method What it does Parameter Type Returns
clear Clears selection
contract Contracts the selection by UnitValue
copy Copies selection to the merge as Boolean
clipboard
cut Cuts current selection
to the clipboard
deselect
expand Expands selection by as UnitValue
feather Feathers edges of by as UnitValue
selection
198 Selection JavaScript Reference Guide
opacity as Long
preserveTransparency as Boolean
grow Grows selection to tolerance as Long
include all adjacent antiAlias as Boolean
pixels falling within the antiAlias.CRISP
specified tolerance antiAlias.NONE
range antiAlias.SHARP
antiAlias.SMOOTH
antiAlias.STRONG
inverting as Boolean
resize horizontal as Double
vertical as Double
anchor as AnchorPosition
AnchorPosition.BOTTOMCENTER
.AnchorPosition.BOTTOMLEFT
AnchorPosition.BOTTOMRIGHT
AnchorPosition.MIDDLECENTER
AnchorPosition.MIDDLELEFT
AnchorPosition.MIDDLERIGHT
AnchorPosition.TOPCENTER
AnchorPosition.TOPLEFT
AnchorPosition.TOPRIGHT
resizeBoundary Scales the boundary of horizontal as Double
selection vertical as Double
anchor as AnchorPosition
AnchorPosition.BOTTOMCENTER
.AnchorPosition.BOTTOMLEFT
AnchorPosition.BOTTOMRIGHT
AnchorPosition.MIDDLECENTER
AnchorPosition.MIDDLELEFT
AnchorPosition.MIDDLERIGHT
AnchorPosition.TOPCENTER
AnchorPosition.TOPLEFT
AnchorPosition.TOPRIGHT
rotate angle as Double
anchor as AnchorPosition
AnchorPosition.BOTTOMCENTER
.AnchorPosition.BOTTOMLEFT
AnchorPosition.BOTTOMRIGHT
AnchorPosition.MIDDLECENTER
AnchorPosition.MIDDLELEFT
AnchorPosition.MIDDLERIGHT
AnchorPosition.TOPCENTER
AnchorPosition.TOPLEFT
AnchorPosition.TOPRIGHT
200 Selection JavaScript Reference Guide
feather as Double
antiAlias as Boolean
antiAlias.CRISP
antiAlias.NONE
antiAlias.SHARP
antiAlias.SMOOTH
antiAlias.STRONG
selectAll
selectBorder Selects the border of width as UnitValue
the selection
similar Grows selection to tolerance as Long
include pixels antiAlias as Boolean
throughout the image antiAlias.CRISP
falling within the antiAlias.NONE
tolerance range antiAlias.SHARP
antiAlias.SMOOTH
antiAlias.STRONG
mode as ColorBlendMode
ColorBlendMode.BEHIND
ColorBlendMode.CLEAR
ColorBlendMode.COLOR
ColorBlendMode.COLORBURN
ColorBlendMode.COLORDODGE
ColorBlendMode.DARKEN
ColorBlendMode.DIFFERENCE
ColorBlendMode.DISSOLVE
ColorBlendMode.EXCLUSION
ColorBlendMode.HARDLIGHT
ColorBlendMode.HUE
ColorBlendMode.LIGHTEN
ColorBlendMode.LINEARBURN
ColorBlendMode.LINEARDODGE
ColorBlendMode.LINEARLIGHT
ColorBlendMode.LUMINOSITY
ColorBlendMode.MULTIPLY
ColorBlendMode.NORMAL
ColorBlendMode.OVERLAY
ColorBlendMode.PINLIGHT
ColorBlendMode.SATURATION
ColorBlendMode.SCREEN
ColorBlendMode.SOFTLIGHT
ColorBlendMode.VIVIDLIGHT
opacity as Long
preserveTransparency as Boolean
translate Moves the position deltaX as UnitValue
relative to its current deltaY as UnitValue
position
translateBoundary Moves the boundary of deltaX as UnitValue
selection relative to its deltaY as UnitValue
current position
202 Selection JavaScript Reference Guide
Sample Script
The following selection script creates a new document by dividing an 800 pixel board into 100 x 100
pixel squares.
The checkerboard is created by iterating through an array of alternating selections in the shape of
squares. One alternating selection of squares is filled with a foreground color from the palette.
Then the procedure is inverted and the other selection of squares is filled with a background color
from the palette. The squares are then de-selected to remove the “marching ants”.
Note: For this script to be effective, the foreground and background colors of the current palette
much be different colors.
Code (Selection.js)
app.preferences.typeUnits = TypeUnits.PIXELS;
app.displayDialogs = DialogModes.NO;
SGIRGBSaveOptions
Properties
Property Access Value Type What it is
alphaChannels R/W Boolean save alpha channels
spotColors R/W Boolean save spot colors
206 SolidColor JavaScript Reference Guide
SolidColor
Properties
Property Access Value Type What it is
cmyk R/W CMYKColor return a grayscale representation of the
color
gray R/W GrayColor return a grayscale representation of the
color
hsb R/W HSBColor return a grayscale representation of the
color
lab R/W LabColor return a grayscale representation of the
color
model R/W ColorMode color model
ColorMode.CMYK
ColorMode.GRAYSCALE
ColorMode.HSB
ColorMode.LAB
ColorMode.NONE
ColorMode.RGB
Methods
Method What it does Parameter Type Returns
isEqual Returns true if the color as SolidColor Boolean
provided color is
visually equal to this
color
JavaScript Reference Guide SubPathInfo 207
SubPathInfo
Properties
Property Access Value Type What it is
closed R/W Boolean is this path closed?
entireSubPath R/W Object all the sub path item's path points
operation R/W ShapeOperation sub path operation on other sub paths
208 SubPathItem JavaScript Reference Guide
SubPathItem
Properties
Property Access Value Type What it is
closed RO Boolean is this path closed?
operation RO ShapeOperation sub path operation on other sub paths
parent RO Object the object's container
pathPoints RO PathPoints
JavaScript Reference Guide SubPathItems 209
SubPathItems
Properties
Property Access Value Type What it is
length RO Long number of elements in the collection
parent RO Object the object's container
210 TargaSaveOptions JavaScript Reference Guide
TargaSaveOptions
Properties
Property Access Value Type What it is
alphaChannels R/W Boolean save alpha channels
resolution R/W TargaBitsPerPixels number of bits per pixel ( default:
TargaBitsPerPixels.SIXTEEN TargaBitsPerPixels.TWENTYFOUR )
TargaBitsPerPixels.THIRTYTWO
TargaBitsPerPixels.TWENTYFOUR
TextFont
Properties
Property Access Value Type What it is
family RO String the family of the font
name RO String the name of the font
parent RO Object the object's container
postScriptName RO String this is the string used to assign a font to a
text item.
style RO String the style of the font
212 TextFonts JavaScript Reference Guide
TextFonts
Properties
Property Access Value Type What it is
length RO Long number of elements in the collection
parent RO Object the object's container
Methods
Method What it does Parameter Type Returns
getByName Get the first element in name as String TextFont
the collection with the
provided name
JavaScript Reference Guide TextItem 213
TextItem
Properties
Property Access Value Type What it is
alternateLigatures R/W Boolean use alternate
ligatures?
antiAliasMethod R/W Anti Alias
autoKerning R/W AutoKernType options for auto
AutoKernType.MANUAL kerning
AutoKernType.METRICS
AutoKernType.OPTICAL
autoLeadingAmount R/W Double percentage to use for
auto leading
baselineShift R/W UnitValue baseline offset of text
(unit value)
capitalization R/W TextCase the case of the text
TextCase.ALLCAPS
TextCase.NORMAL
TextCase.SMALLCAPS
color R/W SolidColor color of text
contents R/W String the text in the layer
desiredGlyphScaling R/W Double
desiredLetterScaling R/W Double
desiredWordScaling R/W Double
direction R/W Direction text orientation
Direction.HORIZONTAL
Direction.VERTICAL
fauxBold R/W Boolean use faux bold?
fauxItalic R/W Boolean use faux italic?
firstLineIndent R/W UnitValue (unit value)
font R/W String text face of the
character
hangingPuntuation R/W Boolean use Roman Hanging
Punctuation?
height R/W UnitValue the height of
paragraph text (unit
value)
horizontalScale R/W Long horizontal scaling of
characters (in percent)
214 TextItem JavaScript Reference Guide
Methods
Method What it does Parameter Type Returns
convertToShape Converts the text item
and its containing layer
to a fill layer with the
text changed to a
clipping path
createPath Creates a work path
based on the text
object
JavaScript Reference Guide TiffSaveOptions 217
TiffSaveOptions
Properties
Property Access Value Type What it is
alphaChannels R/W Boolean save alpha channels
annotations R/W Boolean save annotations
byteOrder R/W ByteOrder Default value is 'Mac OS' when running on
ByteOrder.IBM MacOS, and 'IBM PC' when running on a
ByteOrder.MACOS PC
embedColorProfile R/W Boolean embed color profile in document
imageCompression R/W TIFFEncoding compression type ( default:
TIFFEncoding.JPEG TIFFEncoding.NONE )
TIFFEncoding.NONE
TIFFEncoding.TIFFLZW
TIFFEncoding.TIFFZIP
jpegQuality R/W Long quality of produced image. Only valid for
JPEG compressed TIFF documents ( 0 - 12 )
layerCompression R/W LayerCompression should only be used when you are saving
LayerCompression.RLE layers
LayerCompression.ZIP
layers R/W Boolean save layers
saveImagePyramid R/W Boolean ( default: false )
spotColors R/W Boolean save spot colors
transparency R/W Boolean
218 xmpMetadata JavaScript Reference Guide
xmpMetadata
Properties
Property Access Value Type What it is
parent RO Object the object's container
rawData R/W String raw XML form of file information
7
JavaScript Syntax
JavaScript is a powerful, object-oriented scripting language that was first developed by Netscape
Communications to enhance web-page interactivity. Originally named LiveScript, JavaScript
actually has very little to do with Java. Although it uses a language syntax similar to Java (or to C,
for that matter) it is a language of its own, with rules that are often very different from those found
in Java.
JavaScript is an interpreted language. Before you can run your programs in C, C++ or Java, you
need to create a source file, then run a compiler program that translates the source file into an
executable file containing machine code instructions. In a JavaScript environment, however, all
commands and program statements are executed as soon as you type them in.
Originally designed for Netscape's browser software, JavaScript has rapidly evolved to become a
widely used, general-purpose programming language. It is now accepted as a standard under
ISO-16262 of the International Standards Organization. (The first industry-standard version of the
language, endorsed by the European Computer Manufacturers Association, was known as
ECMAScript). The core language has undergone several revisions, the most current being version
1.5.
JavaScript is designed to use the Unicode character set. Therefore, you are free to use your local
characters as long as they fit into the Unicode character set.
219
220 Core JavaScript Language Features JavaScript Reference Guide
Identifiers
An identifier is a name that appears in JavaScript code. Identifiers are used for the names of
variables, functions and labels. An identifier must begin with a letter, an underscore or a dollar
sign, subsequent characters can also include digits. Thus, myVar1, _myFunction, $my_Var17 are all
legal identifiers. Identifiers can contain Unicode characters, so the identifier "" is perfectly legal.
Case Sensitivity
The JavaScript language is case sensitive, the identifier myField is considered different from
myfield. As a result, great care must be taken when typing program statements, an awareness of the
case sensitivity of the language is very important.
Semicolons
The semicolon (;) is used to separate JavaScript statements. If the statements are on separate lines,
the semicolon is optional.
x = 1
y = 2
If the statements are on the same line, which is not good practice, the semicolon separator is
required:
x = 1; y = 2
x = 17;
y = x + 1;
z = y * y;
Comments
Comments can be inserted into JavaScript code using either the C++ or C-style commenting
protocol. Any text between a double-slash (//) and the end of a line will be ignored by JavaScript.
Also, any text between /* and */ will be treated as a non-executable item (or comment). The
following are valid comment styles:
Comments are extremely important tools because they make programs much more readable and
easier to maintain. JavaScript uses a succinct, C-like syntax, which means a lot can be
accomplished in just a few lines of code.
JavaScript can be quite compact, but nearly indecipherable and hard to debug. Comment the code
liberally as it is written: explain the goal of each code segment, document the parameters used, list
any dependencies, or explain the reasoning used to write the code. The resulting commented code
will make it much easier to read, maintain, extend or debug at a later time.
222 Data Types JavaScript Reference Guide
Data Types
JavaScript supports primitive (core) data types—such as booleans, numbers, and strings—as well
as composite data types, like objects, arrays and functions. The primitive data types are used most
often; consequently, it is important to understand these types and how JavaScript interprets them.
Numbers are represented using standard scientific notation, for example, 17, -88, 3.14159, or
6.023e+23. Unlike some other languages, JavaScript does not distinguish between integer or
floating-point values. In JavaScript, all numbers are represented internally as 64-bit IEEE floating-
point values. In base-ten terms, there are about 20 digits of precision in which to work, which
ought to be adequate for most applications.
Note that integer values should not be written with leading zeros in JavaScript. JavaScript
interprets '021' as the octal representation of the base-ten number 17. (In addition to octal triplets,
hexadecimal numbers can be represented using the '0x' prefix plus two hexadecimal digits; for
example, 0xFF represents a value of 255.)
JavaScript recognizes a number of escape sequences for representing characters inside strings that
would otherwise be impossible to represent. The following table summarizes those escape
sequences.
Escape sequences can be exploited to better handle strings with embedded single or double
quotation marks in them, for example:
Other composite data types, such as arrays and functions, are special types of objects. Though
arrays and functions are objects, JavaScript defines a special syntax for handling each of them.
These composite data types are discussed in the following sections.
• All variable names in JavaScript are case-sensitive, which means that a variable named
MyVariable is not the same as one named myVariable.
• A variable name, which is an identifier, must begin with a letter, an underscore, or a dollar
sign. Subsequent characters in a variable name can be letters, digits, underscores or dollar
signs. Thus, address1, address2, _name, $income are all valid variable names. Since JavaScript
supports Unicode, the usage of Unicode characters in a variable name is OK as well.
• Variables created in JavaScript are permanent, within their scope. Once a variable is
declared, you can use the delete operator to delete a variable. For variables declared with the
var statement, there is no way to manually “undeclare” or destroy them. (JavaScript's
224 Data Types JavaScript Reference Guide
Declaration of variables can be made by typing the keyword 'var' followed by the name of the
variable being declared. For example,
var radius;
Several declarations can be made by separating each variable declaration by a comma. For
example,
var radius, pi, circumference, area; // only one var needed here
Declaring a variable, and initializing its value can be accomplished by using the “assignment”
operator. For example,
The following example declares variables for different primitive data types:
After declaring a variable and assigning it a value, it is no longer necessary to preface it with the
var keyword. The data is simply accessed through the variable name.
Here, a string is concatenated with a number. In this case, the JavaScript interpreter converts area,
a number type, into a string type.
It is legal, in JavaScript, to declare a variable without using the 'var' keyword. But since (as we
mentioned) all JavaScript variables must have a scope, this leaves the interpreter in a bit of a
quandary as to how to "scope" a non-'var' variable. The interpreter resolves this problem by
attaching the unscoped variable to the global name space, which has the effect of making the
variable in question "usable" from all points in a program.
JavaScript Reference Guide Data Types 225
Undefined Variables
In JavaScript, as in other languages, any attempt to use a variable in an expression without first
declaring it generates an exception. Consider the following code:
var x = 1;
z = x + y;
where y is a new variable that was not declared anywhere. When these two lines are executed, a
JavaScript exception ReferenceError would be thrown.
JavaScript has relaxed typing rules, but this is not the same as saying that it is an untyped
language. JavaScript does have data types. The operator typeof can be used to identify the data
type of a variable. To test if the variable y has been defined in the document, execute the following
script:
if (typeof y == "undefined")
alert("Undefined variable.");
else {
// the variable is safe to use
}
Here, the predefined alert method is used to put an alert dialog onscreen if the variable being
tested is not defined. Notice that JavaScript uses the C-like “== operator to test for equality. Also
note that strings are compared by value; hence two strings can be compared directly using the “==
operator.
Variables declared with the var keyword do not follow this rule, because the JavaScript interpreter
creates these variables as the var statement is executed. If the var statement did not assign a value
to the variable, its contents are undefined, which is not equal to the variable being undefined.
Actually, JavaScript treats undefined data as being a special value. The predefined global variable
undefined contains this value, and the result of non-existing object properties (as you will see
below) is reported as undefined.
Operators
As in many other programming languages, a large number of operators are built in to JavaScript.
The following table details the available operators; you may notice that there are a few operators
very specific to the JavaScript language.
226 Data Types JavaScript Reference Guide
Unary operators
These are operators that apply to one operand only.
Binary operators
Binary operators concatenate two operands. They are sorted in their order of precedence. If you
are not sure whether one operator takes precedence of the other, use brackets. This example
demonstrates the usefulness of brackets:
Ternary operators
The ternary operator is actually an abbreviation of the if statement. It has the syntax:
The condition is evaluated, and, it if it evaluates to true, the result of the operation is the result of
the true-expression; otherwise, the result is the result of the false-expression. An example:
Assignment operators
The assignment operators are almost at the very bottom of the operator precedence list.
Assignment operations have a value, which is the value of the right-hand operand. Therefore, a
statement like "a=b=c=0" makes perfect sense.
JavaScript has the simple assignment operator "=" as well as compound assignment operators,
which are the assignment operator combined with an arithmetic or logic operator:
A convenient way of defining an object is the object literal. An object literal is a collection of name/
value pairs, set apart by commas, and enclosed in matching curly braces. The name/value pairs
are separated by a colon. For example:
This defines an object with two properties; the property names are question and title. The order in
which the properties are listed is immaterial. Objects can be assigned to variable names, just as
primitive data types can:
Data within the object can be accessed through the “.” notation. As opposed to simple variables,
variables as part of an object are called properties. For example, the value of the question property
of the params object is params.question. It is important to note that params.question, in this example,
behaves much like a variable. Here, params.question represents the string "How are you today?".
params.dflt ="Fine";
Note that you can also use numeric or string constants as property names to define an object; it
depends on whether the property name conforms to the syntax rules of identifiers or not. An
example:
The [] operator can also be used to access the properties of an object. For example,
params["question"] represents the string "How are you today?". Note that the expression enclosed
in the brackets is a string, not an identifier. As will be seen in the paragraphs on the for/in Loop,
this method of accessing the properties and values of an object is quite useful, and, if the above
example, it is the only way to access the properties of myObj.
As was mentioned before, the value of a property can be a primitive data type, a function, an array,
or another object. If a property of an object has as its value a function, that property is referred to
as a method of the object. JavaScript defines a number of objects, each having properties and
methods.
Example: JavaScript defines the String object. String object have a number of methods that work
on the string contained in the String object, like e.g. the charAt method The method is accessed in
the same way as a property, using the “.” notation, for example,
You can also define objects the procedural way, using the Object constructor function:
methods of declaring an array that will be discussed in these paragraphs. Arrays can be declared
using an array literal, or an array constructor.
Example:
// array literal
var myArray1 = [ "This", "is", "ExtendScript", 3.0 ];
var myArray2 = [ 1, "String", { x:1, y:2 } ];
Note that the myArray2 contains a mixture of data types: number, string and object.
// Array constructor
var colors = new Array("red", "green", "blue");
The indexing system is 0-based, the first element of the array has index 0, the second element has
index 1, and so on. To access the elements of an array, the [] operator is used, with the index
number inserted between the brackets. For example
The declaration var myArray = new Array() creates an empty array of length zero. The elements of
myArray are undefined:
One the empty array is declared, elements can be added to it; for example, after the code lines
myArray[0] = "Adobe";
myArray[1] = "Acrobat";
There is no need to supply each element of the array. If you use two consecutive commas, the
element that is missing remains undefined. Note, however, that you will have to use two commas
at the end of the array literal if you want the last array element to be undefined. Examples:
Regular expressions
JavaScript contains a full regular expression object which you can use to parse strings in very
complex ways. The full syntax of regular expressions would be too much for this document;
please refer to more elaborate books about JavaScript. There is a way to declare a regular
expression by enclosing it in slashes:
This statement creates a RegExp object. The object has a number of methods and properties, the
exec() method being the most important one. That method returns an array of matches, the first
element being the match found, and other elements containing the result of enclosed regular
expression captures. Examples:
Functions
A function is a block of JavaScript code that is compiled once, but can be executed many times.
Some of the important points concerning functions include:
There are a number of ways of defining a JavaScript function. Only the most popular style is
presented here. The syntax for defining a function is
The labels functionName and parameter list are replaced by the name of the function that is being
defined, and by the list of parameters of the function, respectively. The following defines a
function mySum and will be used to illustrate the itemized points above.
Here, the values 10 and 7 are passed to the function mySum as its required parameters. The
function then returns the sum of the two passed parameters. In the body definition, a local variable
z is declared. The (local) variable z is unknown outside this function. (Recall the assumption of
this example that the variable z has not been declared anywhere at the top level outside the
function.) To demonstrate this last statement, executing the line
A function need not have any parameters or a return value. For example:
function helloWorld() {
alert("Hello world");
}
JavaScript Reference Guide Functions 233
The helloWorld function simply pop ups an alert box on the screen.
If a function is attached to an object, it is called a method. You can attach a function to an object by
assigning the function name to the property or by declaring the function directly:
The call obj.foo() would pop up the "Hello world" alert box, and the call obj.bar() would pop up the
alert "This is a wonderful world!".
Actually, a function is just a Function object; therefore, you can attach it to whatever object you
like, or move it around, or even store it into an array. Consider this example of an array literal:
fooArray = [
function() { return "One"; },
function() { return "Two"; },
function() { return "Three"; }
];
This creates an array containing three functions. You could call any of these functions by indexing
the array as usual:
If a function is attached to an object, it can use the this keyword to access the object that it is
attached to. An example:
The call obj.getValue() would return 5. If the this keyword was omitted, it would attempt to locate
the variable value in its scope chain; if it was executed within a function body containing the
variable value defined as var, it would use that value, or it would use the value of the global
variable value if present; so the results may become pretty unpredictable.
234 Predefined variables and functions JavaScript Reference Guide
The String object has a number of methods for searching and replacing strings. Some of these
methods use regular expressions. The RegExp object also has methods for searching strings.
In addition to these core objects, applications usually define a large number of objects, again, each
with their own properties and methods used for manipulating the objects.
236 Conditionals and Loops JavaScript Reference Guide
if (expression)
statement // to be executed if expression is true
else
statement // to be executed if expression is false
This construct is very important. The parentheses that surround expression are required. If multiple
statements need to be executed, make sure that matching braces enclose the statements.
Examples:
if (i == 1)
alert("The variable i equals 1");
else
alert("The variable i has a value of " + i);
// testing two conditions: if str equals "Yes" and i is greater than 4
if ((str == "Yes") && (i > 4))
alert("You are granted access!");
else // here, str != "Yes" or i <= 4
alert("You may not enter!");
When testing for equality, the == (equality) or === (identity) operator can be used; for testing
inequality, use != (inequality), or !== (non-identity). Other comparisons include < (less than), >
(greater than), <= (less than or equal) and >= (greater than or equal to).
Compound logic can be accomplished using the logical operators of && (and), || (or) and ! (not).
JavaScript has precise operator precedence; however, in the above example, the logical expressions
are grouped using parentheses to be certain the logic is correct.
Another conditional construct, the switch, can execute code based on a series of mutually exclusive
and exhaustive cases. The syntax for the switch statement is illustrated below:
The switch statement evaluates the expression, myVar, in this case, and tries to match it up with one
of the values listed in the case statements. The switch statement uses the identity operator, ===, to
make the comparisons; consequently, if myVar = "1" (a string value), the above switch would
evaluate to the default case, since (1 === "1") is false. A workaround would be to convert myVar to
a number type.
switch (myNum) {
case 1:
case 2:
case 3: msg = "Between 1 and 3"; break;
default: msg = "This is the default case";
}
alert(msg);
Or, you can use arbitrary complex expressions to express your case:
Loops
Loops enable a block of code to be executed repeatedly under (possibly) different conditions
each time.
while (condition) {
// loop body (JavaScript statements)
}
238 Conditionals and Loops JavaScript Reference Guide
The loop runs repeatedly until the condition is false. JavaScript tests the condition before it executes
the statements inside the loops. An alternate version tests the condition after the statements inside
the loop have been run.
do {
// loop body (JavaScript statements)
} while (condition);
You can leave a loop with the break statement, and you can skip over the remaining statements
inside the loop and have the next check processed with the continue statement.
The initialize part of the for loop is used to initialize some variables that are used in the loop.
(Multiple initializations must be separated with a comma). The test component is evaluated in a
boolean context: If test evaluates to true, the loop body is executed, otherwise, the loop is
terminated. After the loop body has been executed, the increment expression is evaluated. The
increment expression is usually some sort of assignment, for example, i=i+1. (An assignment of the
form i=i+1 is quite common; the more compact ++ operator is often used. The assignment i=i+1 is
equivalent to i++). The enclosing parentheses are required; the grouping braces are required only
if there are multiple lines within the body of the loop. Prematurely exiting a loop can be
accomplished by executing the break statement, and you can use the continue statement to skip the
remainder of the statements inside the loop and proceed to the next increment operation.
Comments on the Example: After the initial three declarations, the prompt method is used to
acquire a response from the user. The return value of this method is assigned to the variable
response. The documentation for this method states that the return value will be the null value if
the user cancels the dialog. A conditional statement is used, the search will occur only if response is
non-null.
• Initialize: The variable i is used to index the loop and it is initialized to 0 with the statement
var i = 0.
• Test: The testing condition is i < colors.length. The loop body is repeatedly executed until the
index i is equal to the length of the colors array.
• Increment: After the loop body is executed, the increment expression, i++, is evaluated,
which increases the value of the index i by one. At this point, the test is evaluated and the
body of the loop is executed again, if i < colors.length, or the loop is exited, if i >= colors.length.
In the loop body, note the use of the break statement. If the ith array element favorably compares
with the user’s response, break is executed. If the user did not guess one of the colors, then on exit
from the loop, the value of i will be colors.length. This fact is exploited to determine whether the
user successfully guessed one of the colors.
The enclosing braces are only required it there are multiple lines of JavaScript code contained
within the loop body. Again, you can use the break statement to exit the loop, or the continue
statement to skip the remaining statements inside the loop.
The for/in loop creates an internal snapshot of the object's properties. Every time the loop is run,
the loop variable receives the name of the next property of this snapshot. You can then use the []
notation to access the contents of that property. Note, however, that most properties and method
of built-in object types are not enumerable; you cannot reach them in a for/in loop.
Since an array is also an object, arrays can be searched using the for/in loop as well.
JavaScript Reference Guide Making code readable: the with statement 241
var data = [
{ value: 111 },
{ value: 222 },
{ value: 333 }
];
function sum (objArray) {
var result = 0;
for (var i = 0; i < objArray.length; i++) {
with (objArray [i]) {
// instead of objArray[i].value
result += value;
}
}
return result;
}
alert (sum (data));
242 Dealing With Exceptions JavaScript Reference Guide
The following code defines a method that attempts to access the variable notThere, causing a
ReferenceError to be thrown. The statement below would try to execute the function and catch the
thrown error.
function testMe() {
return notThere;
}
try {
testMe();
}
catch (e) {
alert (e);
}
finally {
alert ("OK, I am done.");
}
The finally statement is always executed, either after a successful try or after a successful catch
operation.
Error handlers can be written to deal with exceptions thrown by the application and by custom
written JavaScript code. A very common case for throwing an exception is if the underlying object
no longer exists inside the application (i.e. it is dead, but a reference to the object still exists).
Consider the following piece of code:
This will throw an exception when the third line is executed. The document has been closed and
no longer exists. A reference to this document is still being held in myDoc and any attempt to use it
will throw an exception.
If you want to catch multiple different errors or other objects, you can use multiple catch clauses.
The argument of a catch clause can be expanded with an if statement:
Note that, unlike the regular if statement, the conditional expression is not surrounded by
brackets.
JavaScript Reference Guide Dealing With Exceptions 243
For example,:
function throwIt() {
throw "Ouch!";
}
try {
throwIt();
alert ("Nothing appeared to be thrown");
}
catch (e if e instanceof Object) {
// catch all objects
alert ("An object was caught");
}
catch (e if e == "Ouch!") {
// catch the string "Ouch!"
alert ("Ouch! This hurt!");
}
catch (e) {
// catch everything else
alert ("Caught " + e);
}
As demonstrated, a JavaScript program can throw anything, from simple numbers or strings to
complex objects. JavaScript will throw runtime errors as Error objects; there are a number of
specialized objects like ReferenceError or TypeError that are derived from Error. Finally, you have to
use an unconditional catch clause as the last of your catch clauses.
244 Coding conventions JavaScript Reference Guide
Coding conventions
This section contains a set of recommendations for writing JavaScript programs. It is organized as
a set of rules with explanations. You are strongly encouraged to follow these rules.
G PathItems, 177
GalleryBannerOptions, 142 PathPoint, 178
GalleryCustomColorOptions, 143 PathPointInfo, 179
GalleryImagesOptions, 144 PathPoints, 180
GalleryOptions, 145 PDFOpenOptions, 181
GallerySecurityOptions, 146 PDFSaveOptions, 182
GalleryThumbnailOptions, 147 PhotoCDOpenOptions, 183
GIFSaveOptions, 148 Photoshop actions, 81
GrayColor, 149 PhotoshopSaveOptions, 184
PICTFileSaveOptions, 185
H PICTResourceSaveOptions, 186
History class, 3 PixarSaveOptions, 187
HistoryState, 150 Platform interface, 5, 43
HistoryStates, 151 PNGSaveOptions, 188
Home directory, 5, 45 Portability, issues, 49
HSBColor, 152 Predefined core objects, 235
Predefined functions, 234
I Predefined variables, 234
IndexedConversionOptions, 153 Preferences, 189
Interface, 87 Preprocessing statements, 5
PresentationOptions, 193
J Prompt, script, 74
JavaScript syntax, 219 Prompts and alerts, 23
JPEGSaveOptions, 154
R
L RawFormatOpenOptions, 194
LabColor, 155 RawSaveOptions, 195
Layer class, 3 Regular expressions, 231
LayerComp, 156 Resource specification, 18
LayerComps, 157 RGBColor, 196
Layers, 158
LayerSet, 159 S
LayerSets, 162 Script prompt, 74
Loops, 236 Selection, 197
Selection class, 2
M SGIRGBSaveOptions, 205
Modal dialogs, 22 Solid color classes, 4
SolidColor, 206
O Static text element, 14
Object properties, user interface, 31 SubPathInfo, 207
Operators, 225 SubPathItem, 208
SubPathItems, 209
P Syntax, JavaScript, 219
Panel element, 14
Path names, 44 T
PathItem, 164 TargaSaveOptions, 210
JavaScript Reference Guide 247