Change Keyboard Layout AppleScript Stopped Working After Upgrading to Monterey

Hi,
I have the AppleScript below that worked great in Big Sur. But after upgrading to Monterey, it stopped working. Can anyone help me fix it?

Thanks!

changeKeyboardLayout("Squirrel")

on changeKeyboardLayout(layoutName)
	tell application "System Events"
		tell process "TextInputMenuAgent"
			click menu item layoutName of menu 1 of menu bar item 1 of menu bar 2
			click menu bar item 1 of menu bar 2
		end tell
	end tell
end changeKeyboardLayout

If I change layoutName to a number, such as

click menu item 1 of menu 1 of menu bar item 1 of menu bar 2

SD shows

menu item "U.S." of menu 1 of menu bar item 1 of menu bar 2 of application process "TextInputMenuAgent"

image

Which means it is able to get U.S., but the click simulation does not have any effects, i.e., it does not switch the keyboard layouts to U.S..

I also had similar problems after upgrading to Monterey. Sometimes click events from AppleScript are simply ignored. You can try a click at position like this:

tell (click menu item layoutName of menu 1 of menu bar item 1 of menu bar 2)
	set {xPosition, yPosition} to position
	set {xSize, ySize} to size
end tell
click at {xPosition + (xSize div 2), yPosition + (ySize div 2)}

Sometimes, however, even this does not help and only the use of external tools such as clickclick or clicking via AppleScriptObjC can help.

Thanks!
I got a compile error in SD:

If I’m understanding correct, it requires that the menu item to be visible.

The following code works but not ideally. It explicitly clicks the menu item and causes floating windows such as Alfred search window to deactivate.

my changeKeyboardLayoutTo("U.S.")

to changeKeyboardLayoutTo(layoutName)
	ignoring application responses
		tell application "System Events" to ¬
			click menu bar item 1 of menu bar 2 of ¬
				application process "TextInputMenuAgent"
	end ignoring
	
	delay 0.1
	do shell script "killall 'System Events'"
	delay 0.2
	
	tell application "System Events"
		launch
		click menu item layoutName of menu 1 of ¬
			menu bar item 1 of menu bar 2 of ¬
			application process "TextInputMenuAgent"
	end tell
end changeKeyboardLayoutTo

The code in the OP used to work in Big Sur in the background. It will not deactivate the Alfred search window.

I have only replaced the relevant code section to click. This must of course be within the:

tell application "System Events"
		tell process "TextInputMenuAgent"

blocks are located.

I wonder about that. This code actually fixes the problem that Applescript sometimes hangs on clicks up to 10 seconds. But if it works…