Delete Keystroke from AppleScript Context
In Safari, there is a text field, in which, contains name of an image with extension .png, and I have to remove that extension.
Solution
Write a script, in which, simulate Delete(⌫) key 4 times, if preceding characters are .png, thereby removing the extension.
Problem
Here it says that should be done with key code 51 but that doesn't seem work. A Google search came up with other key codes such as 127.
Things to Fix my solution
What is the correct Key Code? Is there a way to find it out yourself like Accessibility Inspector for buttons, fields etc. I tried recording, doesn't work? Does Apple have a official list a of Key Codes?
For those interested, below is the script, nothing fancy:
# Checks and remove .png if exists

tell application &quot;System Events&quot;
    set oldClipboard to the clipboard
    
    repeat 4 times
        key code 123 using {shift down}  # Left Arrow key. Selects last 4 chars
    end repeat
    keystroke &quot;c&quot; using {command down}
    
    set newClipboard to the clipboard as text
    if newClipboard is equal to &quot;.png&quot; then
        #keystroke (ASCII character 127) # Other &quot;code&quot;, doesn't work
        key code 51
        delay 0.1
    end if

    key code 124                         # Right Arrow key, works
    set the clipboard to oldClipboard
end tell
Your script works fine in most apps. Can easily test it in TextEdit to see that. When I said add in dialog boxes to text the flow, mostly what you need to test is that the "if newClipboard is equal to ".png" is getting triggered (not if the text is getting selected.
I would guess that your problem is that in a web form box (which I think you were describing), javascript is slowing down the text response including the copying to clipboard. It is a VERY common problem when scripting copying to clipboard that you need to add a delay after copying in order for the process to complete before the script proceeds. Try this, which simply adds the delay:

tell application "Safari" to activate
delay 1
tell application "System Events"
    set oldClipboard to the clipboard
    repeat 4 times
        key code 123 using {shift down} # Left Arrow key. Selects last 4 chars
    end repeat
    delay .5
    keystroke "c" using {command down}
    delay 2
    set newClipboard to the clipboard as text
    -- display dialog newClipboard
    if newClipboard is equal to ".png" then
        #keystroke # WORKS!!!!!!!!
        key code 51
        delay 0.1
    end if

    key code 124 # Right Arrow key, works
    set the clipboard to oldClipboard
end tell