Reply To: Script to import partial filename

#92529
Oleh Melnyk
Member

there are a lot of things that might cause the problems:
1) you are getting SlugArea variable from the file name, but you are getting this BEFORE file is saved (so there might be wrong file name)
2) you are trying to save document while script are working (getting and setting SlugArea variable) so saving is locked, which might cause the problem
3) you create 2 new event handlers every time you run the script, and they ALL keep working till you remove them manually or till you restart InDesign (!!!) – so if you, for example, started script 5 times – on each “Save” or “Save As” 5 event handlers try to execute…at the same time…
4) maybe something else I am not aware of

try this:


#target indesign;
#targetengine “mysession”;

// https://creativepro.com/topic/script-to-import-partial-filename#post-92526

// every time you run the script you add 2 new event handlers - we need to remove the old ones
try{
if(app.eventListeners.length > 0){
app.removeEventListener("afterSave", myHandler);
app.removeEventListener("afterSaveAs", myHandler);
}
}catch(e){
$.writeln(e);
}

// create "SlugArea" text variable (if it missing)
if(!app.activeDocument.textVariables.item("SlugArea").isValid){
app.activeDocument.textVariables.add({ variableType: VariableTypes.CUSTOM_TEXT_TYPE, name: "SlugArea"});
}

// set default value if varible is empty
if(app.activeDocument.textVariables.item("SlugArea").isValid && app.activeDocument.textVariables.item("SlugArea").variableOptions.contents.length == 0){
app.activeDocument.textVariables.item("SlugArea").variableOptions.contents = "SlugArea (default value)";
}

var myHandler = function(ev){
var fileNameVariable = app.activeDocument.name.match(/[A-Z]{2,5}(?=)/)[0];

// if we found what we were looking for
if(typeof fileNameVariable == "string" && fileNameVariable.length > 2) {
// set proper value for text variable...
app.activeDocument.textVariables.item("SlugArea").variableOptions.contents = fileNameVariable;
}
}

// since we generate SlugArea varibale from the file name - we need to do that AFTER file is saved, and its name was changed...
app.eventListeners.add("afterSave", myHandler);
app.eventListeners.add("afterSaveAs", myHandler);

but you will have to re-save document (Ctrl + S / Cmd + S) manually after slug area is set

This article was last modified on March 1, 2017

Comments (0)

Loading comments...