Skip to main content
Participant
November 2, 2022
Question

Script autostart when opening a file.

  • November 2, 2022
  • 2 replies
  • 250 views

Hi.
I have a simple script that changes text variable to first 13 characters of the file name.
What can i do to autorun this script on every file I'm opening? Pasting it to startup script folder did not help 😞
Here is code i used for this script:

#targetengine "kasyan"

var eventListener = app.addEventListener("afterSave", updateTextVar, false);

function updateTextVar(event) {
	try {
		var doc = app.documents[0];
		var textVarName = "INDEKS";
		var textVar = doc.textVariables.item(textVarName);
		var m = doc.name.match(/.{13}/);

		if (m != null) {
			var custName = m[0];
			
			if (!textVar.isValid) {
				textVar = doc.textVariables.add({variableType: VariableTypes.CUSTOM_TEXT_TYPE, name: textVarName});
				
			}

			if (textVar.variableOptions.contents != custName) {
				textVar.variableOptions.contents = custName;
			}
		}
	}
	catch(err) {}
} 

 

This topic is closed to new replies. Start a new post to keep the conversation going.

2 replies

Legend
November 2, 2022

@Łukasz24983335wax1,

 

Per @Robert Kyle recommended changes, give this a try...

 

#targetengine "session"   
   

app.addEventListener("afterOpen", updateTextVar, false);   
 
function updateTextVar(event) {
	try { if (event.parent.constructor.name == 'LayoutWindow') {       
		var doc = app.documents[0];
		var textVarName = "INDEKS";
		var textVar = doc.textVariables.item(textVarName);
		var m = doc.name.match(/.{13}/);

		if (m != null) {
			var custName = m[0];
			
			if (!textVar.isValid) {
				textVar = doc.textVariables.add({variableType: VariableTypes.CUSTOM_TEXT_TYPE, name: textVarName});
				
			}

			if (textVar.variableOptions.contents != custName) {
				textVar.variableOptions.contents = custName;
			}
		}
	}
}
	catch(err) {}
  }

 

Regards,

Mike

Inspiring
November 2, 2022

Well, first thing is you need the "afterOpen" event, not afterSave. The script does belong in the startup scripts folder; you want to create the event listener when InDeisgn starts. 
The afterOpen event will fire twice. Your function should test the event.target.constructor.name and only proceed  when it's a Window. Or maybe a Document Windiw (I'm not logged in right now).

 Hope this helps

 Bob