Saving script data within document
There is good way to store data within document elements. We can store very long text data into almost every element within InDesign. Data is only visible through scripting, and also can be set just through scripting. This is great way to carry document specific data everywhere we go, because data we set is saved into document. So, let’s see how we can use this great feature.
For example, I’m using this for saving settings for my scripts, so each time I load my script, settings last time I used are loaded automatically. If I’m using script in new document, defaults are loaded from script, and after running, settings are saved in document.
Two important things to remember:
- 1. We can undo it!
- 2. We can’t insert data while ScriptUI window is open.
So, let’s see how to achieve this through scripting. Functions that we are looking for are insertLabel() and extractLabel(). Like I said in beginning, we can insertLabel to almost any object in document, but for now we will take look just for inserting label into document. Inserting label into document was introduced in InDesign CS3.
Function syntax for writing label:
IMPORTANT: If we forget label name, label is LOST! Really?!?! YEAH, REALLY!
Function syntax for reading label:
var myLabel = app.activeDocument.extractLabel('myLabel');
Ok, we set label, and we retrieved data back, and that’s it. Now it all on our needs, and what we want to achieve. Keep your label names unique, so they don’t accidentally match to names that other scripter uses. Thing I do when I want to save more data into single label is to separate values like this:
var myValue = String('value1*value2*value3*value4*value5'); app.activeDocument.insertLabel('myLabel', myValue);
You see that values are separated with ‘*’, but you can use other separator, because if your value contains ‘*’ then you will not be able to separate it back in correct groups. Separating is easily done with simple ‘split()’ like this:
var myLabel = app.activeDocument.extractLabel('myLabel'); myLabel = myLabel.split("*");
Now, myLabel is Array, containing label values, but now separated back to original form.
And the last example:
var myFolder = Folder(app.activeDocument.extractLabel("myLastFolder")); myFolder = myFolder.selectDlg(); if(myFolder != null)app.activeDocument.insertLabel("myLastFolder",myFolder);
Really simple example, but can save lot of time searching for folders. So, first we try to extract our label, and we pass value we got to folder select dialog. Good thing with folder select dialog is that it wont crash if folder we passed don’t exist. And at the end, if we select folder, and confirm it, location we selected is written back in label, so next time we start script, dialog will point to last used location.