nollaf126
nollaf126

Reputation: 160

In InDesign CC 2017 javascript, when using the eventListener "afterOpen", how can I avoid the warning, "No documents are open."?

I'm using InDesign CC 2017 with Mac OS X El Capitan, and want to use a script in my Startup Scripts folder to always perform a check each time I open a file for a certain string in the filePath of that file. If the string is found in the filePath, I simply want to show a message to the user.

After choosing the file to open, I get a warning before the file is loaded. "An attached script generated the following error: No documents are open. Do you want to disable this event handler?"

I figure with an eventListener named "afterOpen", the script wouldn't be triggered until after the file is opened, in which case I figure I shouldn't be getting the warning.

My ideal solution would be to avoid the warning by using more appropriate code (that's what I'm hoping you can help me with), but I'd also be willing to have someone show me how to add code to simply suppress the warning.

#targetengine "onAfterOpen"

main();
function main() {
   var myApplicationEventListener = app.eventListeners.add("afterOpen",myfunc);
}

function myfunc (myEvent) {
    var sPath = Folder.decode(app.activeDocument.filePath);

    if(sPath.indexOf("string in path") >= 0){
        alert("This file is the one mother warned you about.");
    } else {
        alert("This file is good to go!");
    }
}

Thanks in advance for any help. :)

Upvotes: 2

Views: 1187

Answers (1)

Loic
Loic

Reputation: 2193

As the event bubbles through the objects hierarchy, you need to get sure the event parent object is actually the document:

#targetengine "onAfterOpen"

main();
function main() {
	var ev = app.eventListeners.itemByName ( "onAfterOpen" );
	!ev.isValid && app.eventListeners.add("afterOpen",myfunc).name = "onAfterOpen";
}

function myfunc (myEvent) {
	
	var doc = myEvent.parent, sPath;
	if ( !( doc instanceof Document ) ) return;
	
	sPath = decodeURI(doc.properties.filePath);
	if ( !sPath ) return;

	alert( /string in path/.test ( sPath )? 
		"This file is the one mother warned you about." 
		: 
		"This file is good to go!"
	);
}

Upvotes: 3

Related Questions