is now part of CreativePro.com!

JavaScript for the Absolute Beginner

43

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 (https://www.jongware.com/idjshelp.html), or browse them online at MIT (https://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!

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.
  • Jimmy says:

    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!

  • Erwan says:

    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

  • Marc Autret says:

    Welcome to Jongware on InDesign Secrets :) The best scripter ever!

    @+
    Marc

  • John Hawkinson says:

    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.

  • Eugene Tyson says:

    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 :)

  • For more of Theus’s helpful posts, be sure to check out the InDesignSecrets.com forum, he’s all over those threads. :D

    So happy to have you contributing to the blog, Theus!

  • Ray Robertson says:

    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!

  • There should be a dedicated site.

  • Matthew Lala says:

    Awesome. We’re lucky to have someone who’s willing to dig into this underused part of ID.

  • Ray Robertson says:

    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.

  • @Branislav: There actually are several great sites available for InDesign scripting. We want to offer more scripting articles here, but after people become proficient scripters I believe they will want to search out other sites.

    For example, I have seen great scripting articles at Marc Autret’s Indiscripts, Dave Saunder’s JavaScripting InDesign, Harbs’ In-Tools blog, and others.

    • Mahesh says:

      PageMaker scripting anyone?
      Trying to get length of a text with a double quote. Fails.

      l = LenLen(“Mah\”esh”)
      message “Length: ” + str(l)

      • David Blatner says:

        Mahesh: No, InDesign is very different than PageMaker, and requires a completely different kind of scripting.

  • awh says:

    Where’s the big LIKE button! Can’t wait to start learning some of this. Thank you Jongware!!

  • Ryan says:

    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.

  • James Fritz says:

    Great post and a hearty welcome to Jongware as an official ID secrets contributor.

  • Excellent post Jongware!
    Welcome to the InDesignSecrets team!

  • Jongware says:

    @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!

  • Loic says:

    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

  • Amy says:

    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!

  • Dleather says:

    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!

  • 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).

  • Design Instructor says:

    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.

  • @Design Instructor: Ah yes, the ol “do what I want, not what I say” script! Tricky. :)

  • Gfx-Dzine says:

    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!

  • babs press says:

    Thanks for the great article Jongware!!!!
    I never know where I am going to find you ;-)
    Lucky me!!!!!
    babs

  • Kannan H says:

    Hi, this posting is really good and it is being more helpful for me!

  • Kenny says:

    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

  • Kelly Bellis says:

    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:

    https://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.

  • Jongware says:

    Kelly, try this one:

    https://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 :( )

  • Ralph Alcorn says:

    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.

  • Jongware says:

    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.

  • Tom says:

    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

  • Mohamed says:

    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?

  • Juanma P. says:

    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

    • Theunis De Jong says:

      @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.

      • Juanma P. says:

        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.

  • Brian says:

    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?

  • balaji murugesan says:

    i know coding, but i facing lot of issue while working indesign javascript.

    Please anyone refer shortest way of learning.

  • >