How to scroll in New tab in selenium - c#

I opened a new tab by clicking something in selenium in c #. I want to scroll after changing to a new tab, but I get a timeout error.
I get a timeout message and no scroll.
this is c# code.
Used Chrome 79
Chrome option is
options.AddArguments("handlesAlerts=false");
options.AddArguments("--disable-infobars");
options.AddArguments("--no-sandbox");
options.AddArguments("--disable-background-networking");
options.AddArguments("--disable-component-extensions-with-background-pages");
options.AddArguments("--dns-prefetch-disable");
options.AddArguments("--ignore-certificate-errors");
options.AddArguments("--ignore-certificate-errors-spki-list");
options.AddArguments("--ignore-ssl-errors");
options.AddArguments("--allow-running-insecure-content");
options.AddArguments("lang=ko_KR");
if (this.driver.WindowHandles.Count > 1)
{
this.driver.SwitchTo().Window(this.driver.WindowHandles[1]);
}
Utils.sleep(3000);
((IJavaScriptExecutor)this.driver).ExecuteScript("window.scrollBy(0,500);");

you can do this by two steps,
move to the new tab and do the scroll there.
ArrayList<String> AllTabs = new ArrayList<String> (driver.getWindowHandles());
driver.switchTo().window(AllTabs.get(1));
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.scrollBy(0 , window.innerHeight)");
And you can close the tab after you finish.

Please use the below code it will work fine
//Open link in new tab
Actions act = new Actions(driver);
act.KeyDown(Keys.Control).MoveToElement(elementToopenInNewTab).Click().Perform();
// Switch to new tab
driver.SwitchTo().Window(driver.WindowHandles.Last());
//Scroll down in new tab
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
js.ExecuteScript("window.scrollTo(0, document.body.scrollHeight)");
//Move to first tab again
driver.SwitchTo().Window(driver.WindowHandles.First());

Related

DotNetBrowser: Switch between tabs

How to switch between current opened tab to a new tab opened after clicking on a button, using dotnetbrowser? Is it possible?
I'm trying to download a PDF file from a page, that is displayed on a new tab after clicking on a button on the home page. However, all my attempts to retrieve the PDF failed (I've already added the CustomPluginFilter).
EDIT:
Here is the code I use, after getting the page containing the PDF button (after clicking it, a new tab is opened displaying the content of the pdf)
public class CustomPluginFilter : PluginFilter
{
public bool IsPluginAllowed (PluginInfo pluginInfo)
{
if (pluginInfo.MimeTypes.Contains("application/pdf"))
{
return false;
}
return pluginInfo.MimeTypes.Contains("application/pdf");
}
}
DotNetBrowser.BrowserContextParams parameters = new DotNetBrowser.BrowserContextParams(directory);
DotNetBrowser.BrowserContext context = new DotNetBrowser.BrowserContext(parameters);
Browser browser = DotNetBrowser.BrowserFactory.Create(context);
this is where I make the requests to get the page with the button, it is working until here. Next is the steps to get the PDF
browser.PluginManager.PluginFilter = new CustomPluginFilter();
SampleDownloadHandler downloadHandler = new SampleDownloadHandler();
browser.DownloadHandler = downloadHandler;
DOMDocument document = browser.GetDocument();
XPathResult xpath = document.Evaluate(".//table[contains(#id, \"formulario:tabelaIE\")]//tr//a", XPathResultType.FIRST_ORDERED_NODE_TYPE);
DOMElement element = xpath.SingleNode as DOMElement;
element.Click();

To avoid the Windows form to disappear under the task bar when opened as IE page

I am using SHDocVw.InternetExplorer() for open new IE page ,for mainley used height and width set for IE page But my application open as new IE page goes under the tool bar. After i will click it will open which I tried many ways.
Please give any idea to open IE with height and width.
below my code:
var IE = new SHDocVw.InternetExplorer();
object URL = "http://www.northwind.com";
IE.ToolBar = 0;
IE.StatusBar = false;
IE.MenuBar = false;
IE.Width = 540;
IE.Height = 640;
IE.Visible = true;
IE.Navigate2(ref URL);

C# Coded UI testing - enter text into a javascript window.prompt text box

I'm running coded UI tests in Visual Studio Enterprise 2017.
My webpage under test has a javascript popup asking for an e-mail address to be entered. I can locate the confirmationPopup (highlight is drawn correctly), and I can click buttons within it, such as the cancel.
confirmationPopup = new WinWindow();
confirmationPopup.SearchProperties.Add(WinWindow.PropertyNames.ControlType, "Dialog");
confirmationPopup.SearchProperties.Add(WinWindow.PropertyNames.ClassName, "#32770");
confirmationPopup.TechnologyName = "MSAA";
confirmationPopup.Find();
confirmationPopup.DrawHighlight();
var cancelButton = new WinButton(confirmationPopup);
cancelButton.SearchProperties.Add(WinButton.PropertyNames.Name, "Cancel");
Mouse.Click(cancelButton);
What I am struggling to do is enter text in the popup's input box:
var textInput = new WinEdit(confirmationPopup);
textInput.SearchProperties.Add(WinEdit.PropertyNames.ClassName, "Edit");
textInput.TechnologyName = "MSAA";
textInput.DrawHighlight();
textInput.Text = "bill#microsoft.com";
The highlight is drawn around the correct control, but the textInput.Text= line gives an error
Additional information: SetProperty of "Text" is not supported on control type: Window
Any ideas what I'm doing wrong?
Here is an example of interacting with javascript prompt window.
// go to a public site which has a prompt
var window = BrowserWindow.Launch("http://www.javascriptkit.com/javatutors/alert2.shtml");
var contentDiv = new HtmlDiv(window);
contentDiv.SearchProperties.Add(HtmlDiv.PropertyNames.Id, "contentcolumn", PropertyExpressionOperator.EqualTo);
var promptButton = new HtmlInputButton(contentDiv);
promptButton.SearchProperties.Add(HtmlInputButton.PropertyNames.ControlDefinition, "name=\"B4\"", PropertyExpressionOperator.Contains);
promptButton.SetFocus();
Keyboard.SendKeys("{ENTER}");
// now the prompt is showing, find it and set text
var promptWindow = new WinWindow();
promptWindow.SearchProperties.Add(WinWindow.PropertyNames.ControlType, "Dialog");
promptWindow.SearchProperties.Add(WinWindow.PropertyNames.ClassName, "#32770");
promptWindow.DrawHighlight();
var middleWindow = new WinWindow(promptWindow);
middleWindow.DrawHighlight();
var inputBox = new WinEdit(middleWindow);
inputBox.DrawHighlight();
inputBox.Text = "Hello world!";
When using the inspect feature of coded ui, I see there is a middle window. Using it or not, I am able to find the edit.

Selenium webdriver selecting new window c#

Trying to write some test cases using selenium webdriver in c# and have a scenario which i'm unsure of how to resolve
user scenario is searching a table for a patient, select a patient then a new window opens and then assert various items on the window
my issue is i'm unable to select the new window to assert anything from, it's not a pop-up window, it's a full new browser window but it has no window title/name to identify it by, how would I be able to switch driver focus to this window?
thanks in advance
It is really easy in Selenium WebDriver. By using SwitchTo method
driver.SwitchTo().Window(driver.WindowHandles.Last());
See this blog post as well
http://binaryclips.com/2015/03/13/selenium-webdriver-in-c-switch-to-new-window/
This code worked for me. In my case the new window/tab is a PDF that have some weight, so I make some custom waits while it loads.
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(5));
int previousWinCount = driver.WindowHandles.Count;
// Perform the action to open a new Window
wait.Until(driver => driver.WindowHandles.Count == (previousWinCount + 1));
driver.SwitchTo().Window(driver.WindowHandles.Last());
wait.Until(driver => driver.Url.Contains("desired_url_or_a_substring_of_it"));
Note that the driver.Url when the PDF is loading is "about:blank".
IWebDriver _driver = new FirefoxDriver();
_driver.Navigate().GoToUrl("https://www.google.com");
ReadOnlyCollection<string> WindowHandles = _driver.WindowHandles;
foreach (string item in WindowHandles)
{
_driver.SwitchTo().Window(item);
string browserTitle = _driver.Title;
string browserPageSource = _driver.PageSource;
string browserURL = _driver.Url;
}
Use ReadOnlyCollection and handle browser, get the title of your window and compare and get focus on your desire browser window.
If I gather correctly your application will produce the window on it's own without further userintervention. You should be able to wait for the page to load and then you can call your asserts as normal.
Selenium already has your browser-session, so a new window is not an issue for selenium, it is just new content.
foreach (string defwindow in driver.WindowHandles)
{
driver.SwitchTo().Window(defwindow);
if(driver.Title == "")
{
selenium.WindowFocus();
selenium.SelectWindow("");
}
}
"" - indicates your window Title
I've got some code you might like. The quickest solution is to use Popup Finder, but I've made my own method as well. I would never rely on the order the Window Handles are in to select the appropriate window.
Popup Window Finder:
PopupWindowFinder finder = new PopupWindowFinder(driver);
driver.SwitchTo().Window(newWin);
My Custom method. Basically you pass it the element you want to click, your webdriver, and optionally the time to wait before searching after you click the element.
It takes all of your current handles and makes a list. It uses that list to eliminate the previously existing windows from accidentally getting switched to. Then it clicks the element that launches the new window. There should always be some sort of a delay after the click, as nothing happens instantly. And then it makes a new list and compares that against the old one until it finds a new window or the loop expires. If it fails to find a new window it returns null, so if you have an iffy webelement that doesn't always work, you can do a null check to see if the switch worked.
public static string ClickAndSwitchWindow(IWebElement elementToBeClicked,
IWebDriver driver, int timer = 2000)
{
System.Collections.Generic.List<string> previousHandles = new
System.Collections.Generic.List<string>();
System.Collections.Generic.List<string> currentHandles = new
System.Collections.Generic.List<string>();
previousHandles.AddRange(driver.WindowHandles);
elementToBeClicked.Click();
Thread.Sleep(timer);
for (int i = 0; i < 20; i++)
{
currentHandles.Clear();
currentHandles.AddRange(driver.WindowHandles);
foreach (string s in previousHandles)
{
currentHandles.RemoveAll(p => p == s);
}
if (currentHandles.Count == 1)
{
driver.SwitchTo().Window(currentHandles[0]);
Thread.Sleep(100);
return currentHandles[0];
}
else
{
Thread.Sleep(500);
}
}
return null;
}

How to test file download with Watin / IE9?

I'm trying to test file download with Watin 2.1.0 against IE9. I used the suggested code from the accepted answer to the question Downloading a file with Watin in IE9, like this:
var downloadHandler = new FileDownloadHandler(fname);
WebBrowser.Current.AddDialogHandler(downloadHandler);
link.ClickNoWait();
downloadHandler.WaitUntilFileDownloadDialogIsHandled(15);
downloadHandler.WaitUntilDownloadCompleted(200);
However, the downloadHandler.WaitUntilFileDownloadDialogIsHandled(15) call times out. What should I do?
File download dialog doesn't work in IE9 (Windows7) NetFramework 4.0.
Following code snippet might help you resolve the issue:
First you must add references UIAutomationClient and UIAutomationTypes to your test project.
After In Ie9 Tools -> View Downloads -> Options define path to your save folder.
The next method extends Browser class
public static void DownloadIEFile(this Browser browser)
{
// see information here (http://msdn.microsoft.com/en-us/library/windows/desktop/ms633515(v=vs.85).aspx)
Window windowMain = new Window(WatiN.Core.Native.Windows.NativeMethods.GetWindow(browser.hWnd, 5));
System.Windows.Automation.TreeWalker trw = new System.Windows.Automation.TreeWalker(System.Windows.Automation.Condition.TrueCondition);
System.Windows.Automation.AutomationElement mainWindow = trw.GetParent(System.Windows.Automation.AutomationElement.FromHandle(browser.hWnd));
Window windowDialog = new Window(WatiN.Core.Native.Windows.NativeMethods.GetWindow(windowMain.Hwnd, 5));
// if doesn't work try to increase sleep interval or write your own waitUntill method
Thread.Sleep(1000);
windowDialog.SetActivate();
System.Windows.Automation.AutomationElementCollection amc = System.Windows.Automation.AutomationElement.FromHandle(windowDialog.Hwnd).FindAll(System.Windows.Automation.TreeScope.Children, System.Windows.Automation.Condition.TrueCondition);
foreach (System.Windows.Automation.AutomationElement element in amc)
{
// You can use "Save ", "Open", ''Cancel', or "Close" to find necessary button Or write your own enum
if (element.Current.Name.Equals("Save"))
{
// if doesn't work try to increase sleep interval or write your own waitUntil method
// WaitUntilButtonExsist(element,100);
Thread.Sleep(1000);
System.Windows.Automation.AutomationPattern[] pats = element.GetSupportedPatterns();
// replace this foreach if you need 'Save as' with code bellow
foreach (System.Windows.Automation.AutomationPattern pat in pats)
{
// '10000' button click event id
if (pat.Id == 10000)
{
System.Windows.Automation.InvokePattern click = (System.Windows.Automation.InvokePattern)element.GetCurrentPattern(pat);
click.Invoke();
}
}
}
}
}
if you want click 'Save As' replace foreach code with this
System.Windows.Automation.AutomationElementCollection bmc = element.FindAll(System.Windows.Automation.TreeScope.Children, System.Windows.Automation.Automation.ControlViewCondition);
System.Windows.Automation.InvokePattern click1 = (System.Windows.Automation.InvokePattern)bmc[0].GetCurrentPattern(System.Windows.Automation.AutomationPattern.LookupById(10000));
click1.Invoke();
Thread.Sleep(10000);
System.Windows.Automation.AutomationElementCollection main = mainWindow.FindAll(System.Windows.Automation.TreeScope.Children
,System.Windows.Automation.Condition.TrueCondition);
foreach (System.Windows.Automation.AutomationElement el in main)
{
if (el.Current.LocalizedControlType == "menu")
{
// first array element 'Save', second array element 'Save as', third second array element 'Save and open'
System.Windows.Automation.InvokePattern clickMenu = (System.Windows.Automation.InvokePattern)
el.FindAll(System.Windows.Automation.TreeScope.Children, System.Windows.Automation.Condition.TrueCondition) [1].GetCurrentPattern(System.Windows.Automation.AutomationPattern.LookupById(10000));
clickMenu.Invoke();
//add ControlSaveDialog(mainWindow, filename) here if needed
break;
}
}
Edit:
Also if you need to automate the save as dialog specifying a path and clicking save you can do it by adding this code just before break;
private static void ControlSaveDialog(System.Windows.Automation.AutomationElement mainWindow, string path)
{
//obtain the save as dialog
var saveAsDialog = mainWindow
.FindFirst(TreeScope.Descendants,
new PropertyCondition(AutomationElement.NameProperty, "Save As"));
//get the file name box
var saveAsText = saveAsDialog
.FindFirst(TreeScope.Descendants,
new AndCondition(
new PropertyCondition(AutomationElement.NameProperty, "File name:"),
new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit)))
.GetCurrentPattern(ValuePattern.Pattern) as ValuePattern;
//fill the filename box
saveAsText.SetValue(path);
Thread.Sleep(1000);
//find the save button
var saveButton =
saveAsDialog.FindFirst(TreeScope.Descendants,
new AndCondition(
new PropertyCondition(AutomationElement.NameProperty, "Save"),
new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Button)));
//invoke the button
var pattern = saveButton.GetCurrentPattern(InvokePattern.Pattern) as InvokePattern;
pattern.Invoke();
}
IE9 no longer uses a dialog window for saving files. Instead, it uses the notification bar to prevent focus from being removed from the web site. See http://msdn.microsoft.com/en-us/ie/ff959805.aspx under "Download Manager" for reference.
Unfortunately, this means that the current FileDownloadHandler in WatiN will not work. It instantiates a "DialogWatcher" class per browser instance that is a basic message pump for any kind of child window. When child windows are encountered, the DialogWatcher checks to see if the window is specifically a dialog (which the notification bar is not). If it is a dialog, it then iterates over the registered IDialogHandler instances calling "CanHandleDialog." Even if the notification bar were a dialog, it is of a different Window Style (http://msdn.microsoft.com/en-us/library/windows/desktop/ms632600(v=vs.85).aspx), which is how WatiN detects the type of dialog.
From what I can see, there is no support yet for detecting the IE 9 notification bar and its prompts in WatiN. Until that support is added, you will not be able to automate downloading files in IE9.

Categories