Using SwitchToWindowIndex for Keyboard Input

Currently I’m trying to test a files uploading feature. I had trouble using the built-in uploadFile method so I resorted to using a custom keyword for keyboard input to find the path of a file and press enter for uploading. The webpage need to be brought to the front in order for it to receive the keyboard input. This is what my code looks like,

def uploadFile(TestObject to, String filePath) {  WebUI.click(to);  StringSelection ss = new StringSelection(filePath);  Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);  Robot robot = new Robot();  WebUI.switchToWindowIndex(0);  sleep(3000);  robot.keyPress(KeyEvent.VK_META);  robot.keyPress(KeyEvent.VK_SHIFT);  robot.keyPress(KeyEvent.VK_G);  robot.keyRelease(KeyEvent.VK_META);  robot.keyRelease(KeyEvent.VK_SHIFT);  robot.keyRelease(KeyEvent.VK_G);  robot.keyPress(KeyEvent.VK_META);  robot.keyPress(KeyEvent.VK_V);  robot.keyRelease(KeyEvent.VK_META);  robot.keyRelease(KeyEvent.VK_V);  robot.keyPress(KeyEvent.VK_ENTER);  robot.keyRelease(KeyEvent.VK_ENTER);  sleep(1000);  robot.keyPress(KeyEvent.VK_ENTER);  robot.keyRelease(KeyEvent.VK_ENTER);}

This works fine on Chrome but not on Firefox. I noticed that WebUI.switchToWindowIndex(0) does not work as intended on Firefox. Anybody knows why and how to work around this issue? I’m using macOS if that makes a difference. Thanks!