FWIW, I would handle this by keeping track of the player's current target and using xRefType to find out what it is. When it is a container, set a flag and wait for the activate key (spacebar) to be pressed, then trigger the script.
You can also look at my "Take All" mod and perhaps adapt some of that, but using a filter to only get gold.
Also, for xKeyPressed weirdness, I suggest always calling it twice in succession:
setx pressed to xKeyPressed lkeysetx pressed to xKeyPressed lkey
That seems to clear up any previous key presses that may still be causing it to return true (I have no logical explanation for why that happens, but it does) and just seems to help with the overall reliability of using that function.