Thanks for coming to InDesignSecrets.com, the world's #1 resource for all things InDesign!

JavaScript for the Absolute Beginner

Scripting is one of the most powerful features in InDesign. It can save lots of time: almost anything you can do with the user interface, you can do with scripts, and there are even a few things you can do in scripting that you cannot do from within the user interface. Scripting is also a good way to do accurate placing and to repeat the same action dozens, hundreds, or thousands of times. And of course, it’s fun to make InDesign do things the programmers didn’t think of.

The technical background

There are two parts to a script: the language you write your script in, and the interface to InDesign. The language we’re going to focus on is JavaScript. Or, technically, something called ExtendScript, which is a flavor of Javascript that Adobe Creative Suite applications use.

The interface (how the script talks to InDesign) itself is made up of three parts: objects, properties, and methods.

Objects are the bricks that form the foundation of your document. Your document, for example, is one stone. It lies on top of the application itself (also an object). “Above” the document, you can find things like master pages, pages, and stories. Pages, in turn, contain text frames, which hold some of the stories’ text — etc., up to individual characters. It’s important that you understand the hierarchy of objects, and that you’re clear about what object you’re “talking” to when you are scripting.

Properties are what gives the bricks shape, color, and weight. Each object has different properties. For example, a document has a size and can have any number of pages; a piece of text has color, font, and size; and a color, in turn, has a color model (RGB, CMYK, or Lab) and a value for each of the components in this model.

Methods are actions you can apply on your bricks. Common actions for InDesign are add (such as adding a page to a document), remove (the opposite), and specific InDesign actions such as exportFile, findText, and convertBulletsAndNumberingToText — to name just a few.

InDesign talks to the scripts it’s communicating with through this interface, exposing its objects, properties, and methods to the general public. This is called the Document Object Model or ‘DOM’ for short. The DOM returns values to the calling program, accepts new values, and performs operations on request.

Adobe made sure InDesign’s DOM can interface with a lot of programming languages, so users have the choice for themselves — you can use Visual Basic, Applescript, or JavaScript, and even more exotic languages such as C# or Python. However, there are good reasons to stick to JavaScript: it is a fairly easy language (as things go), it is well documented, you can use any plain text editor to write it with, and, most important, you can run the same script on both Windows and Mac OS X.

Starting with a Simple Script

Let’s take apart a short and sweet one-line script Dave Saunders wrote some years ago (and which was highlighted in a recent blog post):

try {app.layoutWindows[0].zoomPercentage = 140 } catch (e) {};

This sets the zoom of your screen to a certain percentage, and you can set it to any value you find convenient.

To be fair, Dave was showing off a bit when he wrote this script, because in JavaScript there is no such thing as a ‘one-line script’. This was actually a six-line script compacted into one line. Here’s the full, properly indented version:

1       try {
2              app.layoutWindows[0].zoomPercentage = 140;
3       } catch (e)
4       {
5              // Nothing to do here
6       };

For longer scripts, it’s wise to put every logical command on a line of its own, properly indent everything inside grouping curly braces, and add the odd comment or two, because it helps in understanding what happens where and in what order. A curly brace at the wrong place can make all the difference between success and failure; the indenting helps you identify the larger structures.

The core command of this little script is line #2 — this is the command that does all the work. We can read this from left to right, as it first focuses on what object we’re talking about, and then what to do.

First, the “app” part is easy: it instructs the script that it’s going to access some part of the parent application, which is InDesign. The dot after “app” tells javascript that you’re done with that “stone” and are going to specify the next object in the hierarchy, or a property of that object.

What is this “layout window”? InDesign has two kinds of windows: the usual document work view window and the Story Editor’s window; and you can have several of each open at the same time, even all of them viewing the same document. InDesign maintains an active list of all of the opened windows, and always makes sure the very first window (the one numbered “0” because in programming-speak zero is first, not one) is the one that is currently active in the interface.

(By the way, InDesign also has an object called “app.activeWindow”, which always points directly to the active window. But this can be either a story editor or a layout window, and we only want the latter one because that’s the one that can zoom.)

If you inspect the properties of this Layout Window object (I’ll discuss how soon), you can find all of the items one would expect: what page or spread is currently visible, which view or preview mode is active, what layer is selected, and – yes! – what the active zoom level is. All of these properties are unique to each layout window; you can open several windows and set each one to a different page and view mode.

The rest of the script (the part before and after line 2) is a “try – catch” command. That is a JavaScript-specific construction that allows the commands in the top braced section to fail gracefully if something goes wrong. For example, in this case, it’s possible there are no layout windows (because there is no open document), and, rather than giving a nasty bleep and showing an error dialog, this gives the script a chance to continue. The bottom braced section does nothing because in this case there is no point in continuing any further. Those two slashes mean the rest of the line is just a comment (you could type anything you want after those slashes). For larger scripts, you might want to alert the user that something is wrong before giving up. Or, if you know in advance what possibly could go wrong you can even have the script try to correct the error and continue as usual. But that’s advanced scripting.

How to Find What You Need?

InDesign’s scripting model is vast. It’s a credit to the dedication of its programmers, because InDesign’s scripting interface supports almost everything you can do in the interface, and it has by far the best scripting support of all of the software in the entire CS Suite. That comes with a drawback: InDesign CS5 boasts 1,086 classes (objects), with a total of 7,310 methods, and a staggering 16,151 properties. So it’s kind of hard to find what specific object, property, or method you need to achieve your goal.

If you are using Adobe’s own ExtendScript Toolkit Editor, you can find an Object Model Viewer under the Help menu. Alas, it requires quite some work to find your way around it. First, you need to select your version of InDesign in the Browser dropdown list before you can use it; then you can enter “zoom” in the Search field, and you get this:

I clicked “LayoutWindows.zoom()” because I had an inkling of what I was looking for a method named “zoom”, but it appears it’s the wrong one, because if you select “ZoomOptions” in the data card, you get this:

which somehow does not tell you what you wanted to know. Only if you look up “ZoomOptions” (somewhere else!), you will find that these options are those of the View menu: Actual Size, Fit Page, Fit Spread, Show Pasteboard, and Zoom In and Out. Frustrating! We actually need the entry above it: the property named “LayoutWindow.zoomPercentage”:

What is this “LayoutWindow” thing? Enter it in the Search field and you can see it’s part of the Application or a Document, and in this case we can use the Application entry under its usual name “app”.

Apart from being quite clumsy to work with, an obvious drawback of this help system is you have to use the ESTK to write your scripts with, where I prefer a plain text editor (TextPad on my PC, TextWrangler on my Mac; but you can use Notepad or TextEdit “in plain text mode” as well).

Fortunately you don’t have to use ESTK — all of this information is actually stored in a file deep inside InDesign’s data folders, and it’s possible to rewrite it to a more convenient format. So I’ve done that for you! Originally, I used XSLT to reformat the original XML into HTML; soon after that, another scripter named ABC Green showed me how to compile it into a single, convenient Windows Help file.

This file is fully hyperlinked, lists how objects are used in functions, and provides graphic representations of the relations between them:

Sometimes you have to see these relations before they make sense; in this case you can see a Layout Window is sort of a Window, which itself is a part of a Document.

You can view this CHM file natively on any Windows system, or with the help of a viewer app on the Mac (I recommend using Robin Lu’s iChm). Download the file for your version of InDesign from my site (http://www.jongware.com/idjshelp.html), or browse them online at MIT (http://jongware.mit.edu, bandwidth graciously provided by John Hawkinson).

Finding More Information

Obviously, this small primer just scratches the surface of scripting and how to do it. You’ll find more articles on the subject here at indesignsecrets.com as time goes by. Also, in the meantime, check out these resources:

Do you have other suggestions for learning javascript for InDesign? Tell us about them!

Theunis De Jong

Theunis De Jong

Dutchman Theunis de Jong is better known under his nickname "Jongware" and has been bothering people since 1966. Started as pressman's little helper in 1984, fresh from school. Really wanted to work in the graphics industry, so he had no problems starting at the very bottom :-) His computer talents were soon discovered, first by himself (being a math & science buff), then by his boss who quickly promoted him to the typesetter division. Worked with WordPerfect, PageMaker, and now InDesign -- but never with Quark. Well, hardly ever. Tends to dive in deep into technical stuff: PostScript, XML, XSLT, general programming in C++ (for DOS, Windows, and Mac OS X). Wrote programs in pure assembler for Z80, ARM4, 80x86, and 68000 processors. As it appeared, this seems the perfect background for right-brain activities such as Scripting and GREP, two InDesign features he fanatically uses (and occasionally abuses). Or was it left-brain? I always forget. I mean, he always forgets.
Theunis De Jong

Latest posts by Theunis De Jong (see all)

  • - November 30, -0001
Tags
Related Articles
Comments

39 Comments on “JavaScript for the Absolute Beginner

  1. Thanks for posting this article David. I’ve never really delved into the Java-scripting side of inDesign, but I always knew I’d need it sooner or later. I use a lot of pre-scripted… er… scripts for the myriad of repetitive tasks and actions I do everyday, and I’ve often thought to myself: “If only I had a script that would do this, and that, etc etc…”

    Well, guess I’ll be looking into creating my scripts from here on in. Thanks again!

  2. Many thanks, for your posting, I want to learn how to make a script but do not know where to begin. I think your posting is where i start to learn

  3. Hey, Jongware, welcome to InDesign Secrets!

    Generally speaking, I would suggest that w3schools is not a good reference source to use for Javascript. While it initially seems good, and is the top google hit frequently, it has some subtle flaws and problems. There’s been a lot of ranting about them at w3fools.

    Instead, use Mozilla’s Javascript reference: developer.mozilla.org/en/JavaScript/Reference.

  4. This is great!

    Thanks to Jongware, always helpful with a script when needed. And now sharing his knowledge with all of us!

    Can’t wait to learn more :)

  5. Great article, and I really appreciate the workarounds shown for ESTK. As an AppleScript developer, I’ve long been spoiled by Script Debugger, and wondered just how ExtendScript users get by with such a clumsy editor. Love the HTML alternative for the dictionary/object model. Great work!

  6. Actually, I do have some questions if you have a moment.

    What are the alternative languages to use instead of ExtendScript on the Windows platform? I know Visual Basic is still hanging around to a certain degree, but I don’t know what else is available.

    Also, I’m wondering how much of the Creative Suite supports ExtendScript. I was aware of ESTK support for InDesign, Illustrator, Photoshop, and Bridge. But last I knew Acrobat was more pure JavaScript with its own editor. Has this changed in recent versions?

    Many thanks, as I’m not a Windows user, but am often asked these questions. I had a client the other day looking for an ExtendScript developer for Illustrator.

  7. Jongware has helped so many people. Good to see him upgraded in stature to be an actual contributor. Thank you for all the help you have given me over the past couple years and congrats.

  8. @Ray: well I’ve been focusing on the combination of ID and JS for so long, I have no idea of any alternatives. I do use a spot of VB but not too much. I work in a mixed Win/Mac environment so I have to make sure my scripts work for everyone :)

    @all: Thank you so much for this warm welcome!
    A next article is soon to arrive!

  9. Thanks a lot to Jongware, Peter and all that ease access to InDesign Scripting knowledge. I have to quote Peter Kahrel cause its books on that topic are the one who help me starting working in this area.
    As for Jongware, I just can recommend its html documentation which is so great.
    @Branislav, I have been a pro for a long while of some specifi place to gather such knowledge. I think Dave Saunders started a Wiki that never found the audience we expected it would. I also created Scriptopedia in this intention but once again, it’s hard to ask people to work twice as they already give a lot on their own blog. So finally such adventures often end in loneliness and desperation for the genuine author. But let’s greet this new attempt and I am certain that we such talented people in charge (Jongware, Kasyan and all other folks), it will be the one !
    Loic

  10. This is such a good article, it might actually be the kick in the pants I need to get started learning how to script. Thanks Jongware!

  11. I’m still confused. I tried to copy this script in text editor to see what it would do, but I can’t figure out how to save as a script! It just ends up a .txt file.

    C’mon man! I wanna script!

  12. In my InDesignSecrets video for Lynda.com, I showed how copy a script from a post and and save it as a script (and install it), around 7:30 into the 9:00 video, Running a Script.

    But the short story is that you just need to save it with a .jsx extension. The text editing program might argue with you about it, but you can prevail. Worst case scenario is to rename the extension manually in the OS (Windows Explorer or the Finder).

  13. I want to know how to write a script to do the following:

    1) Undo that thing I just did.
    2) Redo as I had intended.

  14. Thanks Jongware for the article. I myself started not so long ago with Photoshop scripting and these kind of primers are really useful!.

    Keep ’em comin’ :)

    Dank je wel!

  15. Hello experts!
    I am new to scripts. users told that script will be helpful in saving time and error consumption!!!

    so I need some script for making PDF and EPS for same file (page) at a time(with same settings).
    (for ex: opening a new document indesign cs5. after completing the page work in indesign i have to export to EPS & PDF. now i am making those eps & pdf manually taking too much of time)
    my kind of work is to make pdf and eps of indesign file nearly 50 to 100pages.
    script will be very helpful for me to run timing consumption.
    Thanks in advance

    Thanks,
    Kenny

  16. Your site looks absolutely marvelous! Thank you very much for all of your work and for all of your kindness in sharing.

    Please note that one link is not working and in spite of that same location being pointed to by even Adobe itself and even in its most recent documentation on CS Scripting, they still haven’t gotten it working:

    http://www.adobe.com/products/indesign/extend.displayTab2.html#Scriptingresources

    The folks at Adobe have other urls pointing to scripting resources that similarly are NOT working as of this date (10.4.2012)

    Lastly, please note that there are sites offering Peter Kahrel’s book(s) for free but that are out of date – see the most recent up-dated version only at O’Reilly – and also they do disservice to him, his publisher and sully your karma.

  17. Kelly, try this one:

    http://www.adobe.com/products/indesign/indepth.displayTab2.html#Scriptingresources

    I found it through Google, but only because I knew exactly what to look for.

    (Possibly this is an ‘old’ page, because CS6 is mentioned under the heading “Adobe InDesign CS5 scripting tutorial” (‘Learn the basics of InDesign CS6 scripting in this detailed tutorial.’), but the PDF actually is for CS5! And it’s made with FrameMaker as well :( )

  18. I’m still fuzzy on the Object Model explanation. I have your excellent object model viewer loaded down, and found LayoutWindow and zoomPercentage. However, in the script you use layoutWindows[0]

    I do understand that layoutWindows[0] represents an instance or item in an array, but what in the Object Model tells me to use
    app.layoutWindows[0].zoomPercentage

    I see that there is a Class LayoutWindows, but I thought case mattered, so this is something different from layoutWindows[0]

    If you could extend your object model explanation just a little further it would help.

  19. Ralph, case does matter — hugely!

    Though it’s not a built-in rule for Javascript, Adobe uses case very consistently across their entire scripting model. Here, it is the difference between the class LayoutWindows (which is only ‘a certain type of data’) and the property layoutWindows (which is an existing variable inside the existing variable ‘app’, and could have had any name).

    There is no match required between the name of a property and the name of its class; a Page is a destinationPage for a HyperlinkPage but for a Bookmark it’s just “destination”.

    If you find a Class that seems to be useful, scroll down in my viewer to the “Element of” list. There you will see in what other Class(es) this one is used, and — most important — under what name.

  20. Hi – I’m trying to run automate InDesign using text data from a database. I have a dynamically created jsx InDesign script that I would like to run in InDesign, but I would like to start the script from the command line in Windows. The database can send an event to start InDesign but I would like to include the name of the jsx script that InDesign will run. Can InDesign run a jsx script from the command line? i.e. InDesign.exe -run my script.jsx
    I will be running multiple scripts and don’t want to start and quit InDesign for each script, so I don’t want to put the script in the startup folder for InDesign.
    Thanks for any suggestions. I’m using InDesign CC 2015 on Windows 8.1

  21. Hi,

    Any one help me. I have excel file with 1000 address data’s that I want to make as a small label in In design. Is there any script for supporting?

  22. I need a script to convert a text box with HTML code inside to a HTMLobject… The way could be de following:

    1) Select text box
    2) Cut all text inside it
    3)Select the empty box with selection tool
    4) go to OBJECT/INSERT HTML
    5) Paste inside the code before we cut from text box
    6) OK and close the INSERT HTML menu

    If the Script works we could change a Text box with HTML code inside to a HTML Objet

    Thank and congratulation for your greats tutorials

    • @Juanma P.: It really sounds like you are asking for someone to write that script for you. That was not the intention of this article! Try it yourself and post in the Scripting Forum if you encounter problems, or ask on a site such as freelancer.com if you don’t want to learn how to write scripts.

      • I apologize if it sounded like a request . I just wanted to know if there is a script with such features because the world of scripts is very large and quite unknown.

  23. I’ve been working on learning Javascript / Extendscript for a little while now, and I’ve actually written some pretty useful ones for my job. However, I find the DOM documentation to be worse than utterly obtuse, especially for someone who is not already a Javascript expert, and I feel I spend far too much time trial-and-erroring my way to a usable script.

    Adobe’s documentation is all but useless IMO, and while Jongware and Gregor’s reformatting are miles better I still find it very difficult to locate the objects, methods and properties I want to use and (more importantly) get the correct syntax for their use.

    Does anyone have any good tips or advice for a newbie on how best to understand how the DOM is structured while browsing it, and how to divine the proper syntax?

Leave a Reply

Your email address will not be published. Required fields are marked *