简体   繁体   中英

Selenium ChromeDriver C# - How to Send Shortcut Keys To Browser

I know that I cannot use key combinations with chromedriver, but can use JavaScript as an alternative. The example below navigates to google.com and opens a new window tab.

IWebDriver driver = new ChromeDriver();
driver.Navigate().GoToUrl("https://google.com");
IJavaScriptExecutor js = driver as IJavaScriptExecutor;
js.ExecuteScript("window.open()"); // Open new browser tab like CTRL + t do

But can't figure out how to send these keyboard combinations...

CTRL + SHIFT + i
CTRL + SHIFT + m

Since you can run arbitrary JavaScript using .ExceuteScript you can use a JavaScript solution to send key presses to the Web page: Is it possible to simulate key press events programmatically?

This only works for shortcuts that the Web page itself handles. Since the examples for shotcuts you gave are actually browser shortcuts the JavaScript solution won't work.

Instead you have to send the keyboard presses to the Web browser directly. This is operating system dependent but under Windows you can use SendMessage to send keyboard presses to another process: Sending keyboard key to browser in C# using sendkey function

Edit: The method above makes it hard to send shortcuts with Shift/Control involved. When under Windows SendKeys ( more info about the syntax ) can be used to send keys to the current foreground window:

// reference System.Windows.Forms
SendKeys.SendWait ("^+{i}"); // CTRL + SHIFT + I
Thread.Sleep (500);
SendKeys.SendWait ("^+{m}"); // CTRL + SHIFT + M

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM