javascriptc#selenium-webdrivershadow-domqueryselector

How to SendKeys within textarea under shadow-root using Selenium C#


I've used this Javascript based code but not working:

string scriptToSendAndPressEnter = @"
let textarea = document.querySelector('#root > div > div > div.chatroom-module__chatroom__eVUaK > div.chatroomEditor-module__editor_area__1UsgR > textarea-ex').shadowRoot.querySelector('textarea');
textarea.focus();
textarea.value = 'this text i want to send';
textarea.dispatchEvent(new Event('input', { 'bubbles': true }));
var keyPressEvent = new KeyboardEvent('keypress', { bubbles: true, cancelable: true, keyCode: 13 });
textarea.dispatchEvent(keyPressEvent);
js.ExecuteScript(scriptToSendAndPressEnter);
Thread.Sleep(5000);

The text is not send. I try to press enter by js but not working.

HTML Snapshot:

enter image description here


Solution

  • The desired element is within a #shadow-root (open) so you need to use Document.querySelector() method and inducing WebDriverWait for the ElementToBeClickable() you can use the following solution:

    new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementToBeClickable((IWebElement)((IJavaScriptExecutor)driver).ExecuteScript("return document.querySelector('textarea-ex').shadowRoot.querySelector('textarea.input')"))).SendKeys("PoCoNoi");