Stay Open App: Run Script when a document is opened

I have a script that I only want to run whenever an InDesign Document is opened. I know it needs to saved as a Stay Open Application. Could someone tell me the code to make this happen? Am I aiming in the right direction?

script Test
	beep 3
end script

on idle
	tell application "InDesign"
		WHEN A DOCUMENT IS OPENED (I don't know the code for this)
			tell Test to run
		end if
	end tell
end idle

Thanks - slimjim5811

I don’t have inDesign, but the normal structure of a stay-open app goes like this:

on run
	-- do stuff - this runs when the application is started to set things up if necessary. 
	-- Here you could create a list of all the files in the folder and their modifation dates for example.
end run

on idle
	-- In this section, you periodically check names of windows and compare them to your list. If one has changed you do your thing.
	return 60 -- do this every 60 seconds
end idle

on quit
	-- do stuff - assumes something in the idle handler would cause the application to quit from within or that you want to save something or do something when the itself is quit in the dock.
	continue quit -- must be here!
end quit

So in general, you’ll be polling inDesign for the names of its open documents and if the list changes, do your thing.

So the Stay Open App relies on time, i.e. every 60 seconds? (I realize this can be changed) Can’t it monitor InDesign so that when a document is opened, the script runs automatically?

I don’t know about InDesign specifically but I have that exact thing running with MultiAd Creator. Check the library for something along the lines of “attached scripts”. I will need to run this in the future so if you work it out please post your solution.