Albert
Albert

Reputation: 68240

AppleScript: strange error about non-defined variable

Sometimes, I get this error:

./mac/get_foregroundapp_info.scpt:254:265: execution error: The variable window_name is not defined. (-2753)

This is strange because I cannot see how the variable is not defined. This is the code:

global frontApp, frontAppName, idleTime, window_name

tell application "System Events"
    set frontApp to first application process whose frontmost is true
end tell

set window_name to ""
try
    set window_name to name of front window of frontApp
end try
if window_name = missing value then
    set window_name to ""
end if

The error appears in the line if window_name ....

But it appears only rarely, maybe in about 2-5% of the cases.

It seems to appear more often / always (?) when I keep the Command-key pressed down and mouse hold over some link in Chrome. No idea if that is completely random behavior now or in any way related.


Edit: It seems to appear also always when I have an image opened with Preview. Strangely it seems to work if I open a PDF with Preview.


As Chuck pointed out, it is possible to catch this 'undefined-variable'-error with another try block.

But my main question actually here is: Why is the variable undefined? What does that mean? Because as I see it, it must be defined at that place.


(Btw., this code about getting the window title has several drawbacks. One of them is described here. It also doesn't always work because of this. See another solution here which seems to always work and also without such strange errors.)

Upvotes: 2

Views: 2932

Answers (3)

WINSergey
WINSergey

Reputation: 2005

I find solution, that says me "Error -2753" is a fake error. Bacause my solution is find and added correctly block

  tell application "PrettyApp"
  end tell --PrettyApp 

Upvotes: 0

Chuck
Chuck

Reputation: 4902

Although I don't know why you're getting the error, have you tried something like this?

try
    set window_name to name of front window of frontApp
on error
    set window_name to ""
end try

or more in keeping with what you already have

set window_name to ""
set window_name to name of front window of frontApp
try
    if window_name = missing value then set window_name to ""
on error
    set window_name to ""
end try

Upvotes: 0

Chuck
Chuck

Reputation: 237100

It sounds like an error is cropping up in the try block. Try putting an error handler in there or getting rid of the try block, because right now it will just make the variable not get defined and then you'll get the error you're seeing on the next line.

Upvotes: 1

Related Questions