Safari pop up trigger

I would like to trigger a script when I get a pop up from Safari. I was thinking of writing a script that would compare index values. However I can’t think of a way of doing this without using a repeat loop until the alert is triggered. Is there a javascript function that would help me here? I also want to make the script unobtrusive to my computing ( I would like to be able to use Firefox-Chrome without taking focus away from the activate/repeat loop needed in Safari).

Does anyone have any better ideas of how to do this?

The script has to remain running in order for this to work, however:

You could use the IDLE command in applescript, and have the script run at startup.

Something like:

on idle

tell application "Safari"
	if the (count of windows) is greater than 1 then
		set window_name to name of front window
		
		
		--DO SCRIPT ACTIONS HERE
		
		display dialog "Safari has a new window open: " & window_name giving up after 3 --example

		--Place Script ACTIONS above 
	end if
end tell
delay 10 

end idle

Things to note:
If you use more than one safari window, you would need to increase the number ‘1’ to something higher.
Or, if you know the title of the alert box, you can change the count to ‘0’ and add

if window_name is "title of window" then 
-- DO SCRIPT ACTIONS 
End If

Also,. when you save this script, you will need to Save it as an APPLICATION, and you will have to save as ‘STAY OPEN’ or it will quit without repeating.