Hello Diana,
It sounds like the onBeforeRefresh script you wrote triggers a communication with the backend that makes the backend move to a different screen. This ok and normal, but unfortunately not obvious.
Change your script to check what screen you are on before it returns and if the screen has changed have the script press the back button (or whatever you have to do to go back to your desired screen). You can use session.info.screenNumber/transaction/program to determine "where" you are. When you are sure that your script has navigated back end it with "return true;".
Regards,
Clemens