Facing an issue with downloading PDF files using JavaScriptExecutor:
I am trying to automate the process of downloading a PDF file in a new window using JavaScriptExecutor. The online PDF viewer window has a toolbar section with options like print and download. Manually, I can click on the download button to save the PDF. However, when I tried to automate this process by inspecting the nested shadow root element, I encountered an exception "Cannot read properties of null(reading 'ShadowRoot')". I have attached screenshots of the DevTool Console for reference.
Screenshots of DevTool Console
Here is the code snippet I used:
IWebDriver driver;
driver.FindElement(By.Xpath("Xpath_of_PDF_Link")).Click();
driver.SwitchTo().Window(driver.WindowHandles.Last());
Thread.Sleep(2000);
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
IWebElement downloadButton = (IWebElement)js.ExecuteScript("return document.querySelector(\"#viewer\").shadowRoot.querySelector(\"#toolbar\").shadowRoot.querySelector(\"#downloads\").shadowRoot.querySelector(\"#download\")");
Thread.Sleep(1000);
var element = "argument[0].click()";
js.ExecuteScript(element,downloadButton);
Screenshots of devTool attached below
Looking for suggestions or solutions on how to resolve this issue. Any insights would be helpful as I am new to programming. Feel free to ask for any additional information if needed. Thank you in advance.