Maximize browser window in LeanFT - java

I am looking for some solution, like this in Selenium WebDriver:
ChromeOptions options = new ChromeOptions();options.addArgument("--start-maximized");
So browser window should be maximized when test is executed.
I found a profile based solution for this problem, but it opens a lot of tabs, which is maybe caused by escape characters.
#Test
public void chromeWithProfileLaunch() throws Exception {
String profileDir = "--user-data-dir=\"c:\\Temp\\profile1\""; //should be different folder every time
String leanftChromeExtension = "--load-extension=C:\\Program Files (x86)\\HPE\\LeanFT\\Installations\\Chrome\\Extension"; //to load the LeanFT extension
String homePage = "www.google.com"; //the homepage to start with
new ProcessBuilder("C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe", profileDir, leanftChromeExtension, homePage)
.start();
Thread.sleep(2000); //wait for Chrome process to load
Browser openedBrowser = BrowserFactory.attach(new BrowserDescription.Builder().title("Google").type(BrowserType.CHROME).build());
Verify.areEqual(homePage, openedBrowser.getURL());
}

I don't know about maximized but LeanFT supports putting the browser in fullScreen mode.

LeanFT doesn't support maximize() out of the box yet.
However, you could use sendKeys() method.
I'm not entirely sure if you can to it on the browser instance directly, or you need to getPage() first, but you can definitelly send Super key (win key) + ↑ as specified here. ↓ for restoring back to the initial state.
Here's an example using sendKeys with Java SDK if you need it.

Related

Appium XCUITest iOSDriver sendkeys() not working

TLDR:
sendKeys() not working in web application text field, but only with IOSDriver/XCUITest and only on my web app's page. When running the same test in an Android simulator it works fine on my page, and everywhere else that I've tested (google and ask.com search inputs), but when I test in an iOS simulator, sendKeys() does not work on my web app's page, but works everywhere else (google and ask.com) and I have no idea why.
Capabilities config file:
["Safari", "12.2", "iOS", "iPhone Simulator", "XCUITest", "1.12.1"]
The test:
public class AppiumFieldsTest extends TestBase {
#Test(dataProvider = "appium", groups = "Appium", description = "appium fields test")
public void appiumFieldsTest(String browser, String version, String platform, String device, Method method, String automationName, String appiumVersion) throws Exception {
IOSDriver<WebElement> driver;
DesiredCapabilities caps = new DesiredCapabilities();
caps.setCapability(MobileCapabilityType.PLATFORM_NAME, platform);
caps.setCapability(MobileCapabilityType.PLATFORM_VERSION, version);
caps.setCapability(MobileCapabilityType.DEVICE_NAME, device);
caps.setCapability(MobileCapabilityType.AUTOMATION_NAME, automationName);
caps.setCapability(MobileCapabilityType.BROWSER_NAME, browser);
caps.setCapability("autoAcceptAlerts", true);
caps.setCapability("connectHardwareKeyboard", false);
caps.setCapability("sendKeyStrategy", "oneByOne");
System.out.println(caps);
String url = "http://127.0.0.1:4723/wd/hub";
driver = new IOSDriver(new URL(url), caps);
driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);
driver.get("https://dev-app.pactsafe.com/sign?r=5cd32b47e89fc12f110449ca&s=5b2a6a597a7a3c1e4fa39c0b&signature=kto0Xohrz52ss7kc5z6t0grRbzUPsg6TrfbCbKtRuC5nQM82lNEhFL-zPgN7LaTvGG8mhuifNSc0nayvch1Rgc858Ptx8yRRD9MWJSoD4mEuHFg7LmJ-FHP~UsVEypv-gwwy-6N14BnhdkN94OZ73Kq9mBfS8QGlYKTqa76uclW0FIdnclRfA8NvK0z8CxjPcA8Luv9orw6Ye7wEuHAGqhqFURa15WeFrjrFKW9PNf6NkLVURNvOwqH4xBsfJubCkETMfjtnD4xT7PFSpgykAuU-Av0HehxCFNCYaHmyj5qvB3l9h7xgm8KKoSOO0c9VH1HpnLtwG6KAwwItawcsjg__");
String textFieldtext = "some random text";
Thread.sleep(10000);
WebElement ele = driver.findElementByXPath("//*[#data-name=\"field-5b6305f656bcff936a3c53ca\"]");
ele.click();
Thread.sleep(3000);
ele.sendKeys(textFieldtext);
Assert.assertEquals(ele.getAttribute("data-value"), textFieldtext);
...
...
...
I am trying to do a .click() then a .sendKeys() on the first field at the top of the page, but it is not sending any text. If you run the test you can see that the field is actually being clicked, as it turns a darker blue color, as expected, but then then the sendKeys() function does nothing. Also, when testing on Android, the keyboard opens on click() but not on iOS.
I've tried all the different sendKeyStratey capabilities and still nothing.
I've tried different iOS simulators and appium/safari versions, and still get the same results.
I've tried setting the connectHardwareKeyboard to true, as well as false, and still the same results.
I've added Thread.sleep() in-between commands - nuthin
And again, testing on android works fine on my app, google and ask, but when testing on iOS, my app does not work, but google and ask do
The appium logs show that it is indeed trying to send the text after successfully finding the element:
[HTTP] {"id":"5000","text":"some random text","value":["s","o","m","e"," ","r","a","n","d","o","m"," ","t","e","x","t"]}
[W3C (bf5882ff)] Calling AppiumDriver.setValue() with args: [["s","o","m","e"," ","r","a","n","d","o","m"," ","t","e","x","t"],"5000","bf5882ff-f1a1-4ce1-bb79-02836762cb88"]
[XCUITest] Executing command 'setValue'
Any and all help/suggestions are greatly appreciated
You can try using one of these options:
setValue() This clears the value before sending the string.
Add maxTypingFrequency capability, this is ONLY for IOS when you notice errors during typing, for example the wrong keys being pressed or visual oddities you notice while watching a test, try slowing the typing down. Set this cap to an integer and play around with the value until things work. Lower is slower, higher is faster! The default is 60.

Mobile emulator Selenium tests fail in Jenkins but not in cmd

I have a test that always fail when running inside Jenkins.
My project includes Selenium webdriver, JAVA, Maven, TestNG, Jenkins, Allure (reports).
I have a few suites of tests with 100+ test cases, and I iterate them through 3 different browsers (the tests run in parallel using TestNG). They all run (using maven command line) and pass in my development laptop, and on the test server when using a command line.
I have 2 problems regarding Jenkins and separated them into 2 questions- one of them is described in this question, and the other (IE11 issue) is here.
The problem starts when running inside Jenkins in the test server!
The test fail in mobile emulator (Chrome browser) - in the test I click on a link to verify that a new window was opened with the correct url.
I tried 3 types of clicks (Selenium click, Actions, JS) and all returned a null handle.
The code:
Here I create the main window handle and click the link:
String mwh = driver.getWindowHandle();
WebElement poweredBy = (new WebDriverWait(driver,10).until(ExpectedConditions.visibilityOfElementLocated(By.xpath(Consts.POWERED_BY_XPATH_1000))));
poweredBy.click();
And this is, part of, the method that gets the handle and verify the new window:
public boolean closePopupWindow(String mwh, String mTitle, String layoutNumber) {
// For IE11- make sure popup blocker is turned off in the options. else it will have only one window handle and fail
boolean isOpenedWindowCorrect = false;
String newWindow = null;
Set<String> handlers = driver.getWindowHandles();
for (String window : handlers) {
if (!window.equals(mwh)) {
newWindow = window;
}
}
// the focus is on the main page. need to switchTo new page and close it
driver.switchTo().window(newWindow);
System.out.println("The focus now is on the NEW window");
String newTitle = driver.getTitle();
System.out.println(newTitle);
This is the error I'm getting:
java.lang.NullPointerException: null value in entry: handle=null
at com.google.common.collect.CollectPreconditions.checkEntryNotNull(CollectPreconditions.java:34)
at com.google.common.collect.SingletonImmutableBiMap.(SingletonImmutableBiMap.java:42)
at com.google.common.collect.ImmutableBiMap.of(ImmutableBiMap.java:73)
at com.google.common.collect.ImmutableMap.of(ImmutableMap.java:123)
at org.openqa.selenium.remote.RemoteWebDriver$RemoteTargetLocator.window(RemoteWebDriver.java:995)
at il.carambola.pages.Page.closePopupWindow(Page.java:786)
Do you think there is a security issue that Jenkins wont open new windows in the browser? Is it VERY slow to open the window?
The same tests PASS when not using mobile emulator. (I have the same test in Chrome and Firefox and it succeed to click and pass the verification).
JDK 1.8.0_162
Jenkins V 2.121.1
Server- AWS t2.large - 8GB RAM, Windows server 2016 Data center, 64bit
It's clear that when your program gets to this line
driver.switchTo().window(newWindow);
that newWindow is still null. The way this is written, it could be a timing issue, and it could be another issue causing the popup to not show up. To make sure it's not a timing issue, I would suggest adding some kind of wait for there to be multiple window handles before you try to switch windows. Something like
(new WebDriverWait(driver,10)).until(d -> d.getWindowHandles().size() == 2);
If that wait fails, then you know the popup is being blocked and can go from there.

Java Selenium Web Scraping Upload Image [duplicate]

I have seen lots of questions and solutions on File upload using Selenium WebDriver on Stack Overflow. But none of them are working for following scenario.
Someone has given a solution as following
// assuming driver is a healthy WebDriver instance
WebElement fileInput = driver.findElement(By.name("uploadfile"));
fileInput.sendKeys("C:/path/to/file.jpg");
But still I can't find window handle. How can I work on that?
I am looking for a solution for the scenario above.
Please check this on any of the following websites.
http://www.uploadify.com/demos/
http://www.zamzar.com/
// assuming driver is a healthy WebDriver instance
WebElement fileInput = driver.findElement(By.name("uploadfile"));
fileInput.sendKeys("C:/path/to/file.jpg");
Hey, that's mine from somewhere :).
In case of the Zamzar web, it should work perfectly. You don't click the element. You just type the path into it. To be concrete, this should be absolutely ok:
driver.findElement(By.id("inputFile")).sendKeys("C:/path/to/file.jpg");
In the case of the Uploadify web, you're in a pickle, since the upload thing is no input, but a Flash object. There's no API for WebDriver that would allow you to work with browser dialogs (or Flash objects).
So after you click the Flash element, there'll be a window popping up that you'll have no control over. In the browsers and operating systems I know, you can pretty much assume that after the window has been opened, the cursor is in the File name input. Please, make sure this assumption is true in your case, too.
If not, you could try to jump to it by pressing Alt + N, at least on Windows...
If yes, you can "blindly" type the path into it using the Robot class. In your case, that would be something in the way of:
driver.findElement(By.id("SWFUpload_0")).click();
Robot r = new Robot();
r.keyPress(KeyEvent.VK_C); // C
r.keyRelease(KeyEvent.VK_C);
r.keyPress(KeyEvent.VK_COLON); // : (colon)
r.keyRelease(KeyEvent.VK_COLON);
r.keyPress(KeyEvent.VK_SLASH); // / (slash)
r.keyRelease(KeyEvent.VK_SLASH);
// etc. for the whole file path
r.keyPress(KeyEvent.VK_ENTER); // confirm by pressing Enter in the end
r.keyRelease(KeyEvent.VK_ENTER);
It sucks, but it should work. Note that you might need these: How can I make Robot type a `:`? and Convert String to KeyEvents (plus there is the new and shiny KeyEvent#getExtendedKeyCodeForChar() which does similar work, but is available only from JDK7).
For Flash, the only alternative I know (from this discussion) is to use the dark technique:
First, you modify the source code of you the flash application, exposing
internal methods using the ActionScript's ExternalInterface API.
Once exposed, these methods will be callable by JavaScript in the browser.
Second, now that JavaScript can call internal methods in your flash app,
you use WebDriver to make a JavaScript call in the web page, which will
then call into your flash app.
This technique is explained further in the docs of the flash-selenium project.
(http://code.google.com/p/flash-selenium/), but the idea behind the technique
applies just as well to WebDriver.
Below code works for me :
public void test() {
WebDriver driver = new FirefoxDriver();
driver.get("http://www.freepdfconvert.com/pdf-word");
driver.findElement(By.id("clientUpload")).click();
driver.switchTo()
.activeElement()
.sendKeys(
"/home/likewise-open/GLOBAL/123/Documents/filename.txt");
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
driver.findElement(By.id("convertButton"));
Using C# and Selenium this code here works for me, NOTE you will want to use a parameter to swap out "localhost" in the FindWindow call for your particular server if it is not localhost and tracking which is the newest dialog open if there is more than one dialog hanging around, but this should get you started:
using System.Threading;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using OpenQA.Selenium;
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll", EntryPoint = "FindWindow")]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
public static void UploadFile(this IWebDriver webDriver, string fileName)
{
webDriver.FindElement(By.Id("SWFUpload_0")).Click();
var dialogHWnd = FindWindow(null, "Select file(s) to upload by localhost");
var setFocus = SetForegroundWindow(dialogHWnd);
if (setFocus)
{
Thread.Sleep(500);
SendKeys.SendWait(fileName);
SendKeys.SendWait("{ENTER}");
}
}
I made use of sendkeys in shell scripting using a vbsscript file. Below is the code in vbs file,
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.SendKeys "C:\Demo.txt"
WshShell.SendKeys "{ENTER}"
Below is the selenium code line to run this vbs file,
driver.findElement(By.id("uploadname1")).click();
Thread.sleep(1000);
Runtime.getRuntime().exec( "wscript C:/script.vbs" );
Find the element (must be an input element with type="file" attribute) and send the path to the file.
WebElement fileInput = driver.findElement(By.id("uploadFile"));
fileInput.sendKeys("/path/to/file.jpg");
NOTE: If you're using a RemoteWebDriver, you will also have to set a file detector. The default is UselessFileDetector
WebElement fileInput = driver.findElement(By.id("uploadFile"));
driver.setFileDetector(new LocalFileDetector());
fileInput.sendKeys("/path/to/file.jpg");
There is a simpler way to solve this then what Slanec described. Hes solution works when you are using an English keyboard, if not you will have a hard time trying to "map" the key for special characters.
Instead of robot.keyPress and robot.keyRelease every single key you can use Toolkit to copy the String to the clipboard and then paste it.
StringSelection s = new StringSelection("Path to the file");
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(s, null);
Robot robot = new Robot();
robot.keyPress(java.awt.event.KeyEvent.VK_ENTER);
robot.keyRelease(java.awt.event.KeyEvent.VK_ENTER);
robot.keyPress(java.awt.event.KeyEvent.VK_CONTROL);
robot.keyPress(java.awt.event.KeyEvent.VK_V);
robot.keyRelease(java.awt.event.KeyEvent.VK_CONTROL);
Thread.sleep(3000);
robot.keyPress(java.awt.event.KeyEvent.VK_ENTER);
First add the file to your project resource directory
then
public YourPage uploadFileBtnSendKeys() {
final ClassLoader classLoader = getClass().getClassLoader();
final File file = new File(classLoader.getResource("yourFile.whatever").getPath());
uploadFileBtn.sendKeys(file.getPath());
return this;
}
Walla, you will see your choosen selected file, and have skipped the file explorer window
Import System.Windows.Forms binary to the test solution and call the following two LOC on clicking the Upload button on the UI.
// Send the file path and enter file path and wait.
System.Windows.Forms.SendKeys.SendWait("complete path of the file");
System.Windows.Forms.SendKeys.SendWait("{ENTER}");
An alternative solution would be to write a script to automate the Open File dialog. See AutoIt.
Also, if you can't "click" the element, my workaround is generally to do this:
element.SendKeys(Keys.Enter);
Hope this helps (Even though it's an old post)
Below code works for me:
// wait for the window to appear
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.alertIsPresent());
// switch to the file upload window
Alert alert = driver.switchTo().alert();
// enter the filename
alert.sendKeys(fileName);
// hit enter
Robot r = new Robot();
r.keyPress(KeyEvent.VK_ENTER);
r.keyRelease(KeyEvent.VK_ENTER);
// switch back
driver.switchTo().activeElement();
You have put double slash \\ for the entire absolute path to achieve this
Example:- D:\\images\\Lighthouse.jpg
Steps
- use sendkeys for the button having browse option(The button which will open
your window box to select files)
- Now click on the button which is going to upload you file
driver.findElement(By.xpath("//input[#id='files']")).sendKeys("D:\\images\\Lighthouse.jpg");
Thread.sleep(5000);
driver.findElement(By.xpath("//button[#id='Upload']")).click();
Use AutoIt Script To Handle File Upload In Selenium Webdriver. It's working fine for the above scenario.
Runtime.getRuntime().exec("E:\\AutoIT\\FileUpload.exe");
Please use below link for further assistance:
http://www.guru99.com/use-autoit-selenium.html
webDriver.FindElement(By.CssSelector("--cssSelector--")).Click();
webDriver.SwitchTo().ActiveElement().SendKeys(fileName);
worked well for me. Taking another approach provided in answer above by Matt in C# .net could also work with Class name #32770 for upload box.
The below one had worked for me
webDriver.findElement(By.xpath("//input[#type='file' and #name='importFile']")).sendKeys("C:/path/to/file.jpg");
Double the backslashes in the path, like this:
driver.findElement(browsebutton).sendKeys("C:\\Users\\Desktop\\Training\\Training.jpg");

Open link in new tab [duplicate]

I have trawled the web and the WebDriver API. I don't see a way to open new tabs using WebDriver/Selenium2.0 .
Can someone please confirm if I am right?
Thanks,
Chris.
P.S: The current alternative I see is to either load different urls in the same window or open new windows.
There is totally a cross-browser way to do this using webdriver, those who say you can not are just too lazy. First, you need to use WebDriver to inject and anchor tag into the page that opens the tab you want. Here's how I do it (note: driver is a WebDriver instance):
/**
* Executes a script on an element
* #note Really should only be used when the web driver is sucking at exposing
* functionality natively
* #param script The script to execute
* #param element The target of the script, referenced as arguments[0]
*/
public void trigger(String script, WebElement element) {
((JavascriptExecutor)driver).executeScript(script, element);
}
/** Executes a script
* #note Really should only be used when the web driver is sucking at exposing
* functionality natively
* #param script The script to execute
*/
public Object trigger(String script) {
return ((JavascriptExecutor)driver).executeScript(script);
}
/**
* Opens a new tab for the given URL
* #param url The URL to
* #throws JavaScriptException If unable to open tab
*/
public void openTab(String url) {
String script = "var d=document,a=d.createElement('a');a.target='_blank';a.href='%s';a.innerHTML='.';d.body.appendChild(a);return a";
Object element = trigger(String.format(script, url));
if (element instanceof WebElement) {
WebElement anchor = (WebElement) element; anchor.click();
trigger("var a=arguments[0];a.parentNode.removeChild(a);", anchor);
} else {
throw new JavaScriptException(element, "Unable to open tab", 1);
}
}
Next, you need to tell webdriver to switch its current window handle to the new tab. Here's how I do that:
/**
* Switches to the non-current window
*/
public void switchWindow() throws NoSuchWindowException, NoSuchWindowException {
Set<String> handles = driver.getWindowHandles();
String current = driver.getWindowHandle();
handles.remove(current);
String newTab = handles.iterator().next();
locator.window(newTab);
}
After this is done, you may then interact with elements in the new page context using the same WebDriver instance. Once you are done with that tab, you can always return back to the default window context by using a similar mechanism to the switchWindow function above. I'll leave that as an exercise for you to figure out.
The Selenium WebDriver API does not support managing tabs within the browser at present.
var windowHandles = webDriver.WindowHandles;
var script = string.Format("window.open('{0}', '_blank');", url);
scriptExecutor.ExecuteScript(script);
var newWindowHandles = webDriver.WindowHandles;
var openedWindowHandle = newWindowHandles.Except(windowHandles).Single();
webDriver.SwitchTo().Window(openedWindowHandle);
I had the same issue and found an answer. Give a try.
Robot r = new Robot();
r.keyPress(KeyEvent.VK_CONTROL);
r.keyPress(KeyEvent.VK_T);
r.keyRelease(KeyEvent.VK_CONTROL);
r.keyRelease(KeyEvent.VK_T);
It will open a new tab you can perform your actions in the new tab.
Though there is no API for opening a new tab, you can just create a new instance of WebDriver calling it something slightly different and passing the URL you want in the new tab. Once you have done all you need to do, close that tab and make the new driver NULL so that it does not interfere with the original instance of Webdriver. If you need both tabs open, then ensure you refer to the appropriate instance of WebDriver. Used this for Sitecore CMS automation and it worked.
Thanks for the great idea #Jonathan Azoff !
Here's how I did it in Ruby:
def open_new_window(url)
a = #driver.execute_script("var d=document,a=d.createElement('a');a.target='_blank';a.href=arguments[0];a.innerHTML='.';d.body.appendChild(a);return a", url)
a.click
#driver.switch_to.window(#driver.window_handles.last)
end
There's no way we can create new TAB or handle tabs using web driver / selenium 2.0
You can open a new window instead.
Hey #Paul and who ever is having issue opening a second tab in python. Here is the solution
I'm not sure if this is a bug within the webdriver or because it isn't compatible yet with mutlitab but it is definitely acting wrong with it and I will show how to fix it.
Issue:
well I see more than one issue.
First issue has to do that when you open a 2nd tab you can only see one handle instead of two.
2nd issue and here is where my solution comes in. It seems that although the handle value is still stored in the driver the window has lost sync with it for reason.
Here is the solution by fixing the 2nd issue:
elem = browser.find_element_by_xpath("/html/body/div[2]/div[4]/div/a") #href link
time.sleep(2)
elem.send_keys(Keys.CONTROL + Keys.RETURN + "2") #Will open a second tab
#solution for the 2nd issue is here
for handle in browser.window_handles:
print "Handle is:" + str(handle) #only one handle number
browser.switch_to_window(handle)
time.sleep(3)
#Switch the frame over. Even if you have switched it before you need to do it again
browser.switch_to_frame("Frame")
"""now this is how you handle closing the tab and working again with the original tab"""
#again switch window over
elem.send_keys(Keys.CONTROL + "w")
for handle in browser.window_handles:
print "HandleAgain is:" + str(handle) #same handle number as before
browser.switch_to_window(handle)
#again switch frame over if you are working with one
browser.switch_to_frame("Frame")
time.sleep(3)
#doing a second round/tab
elem = browser.find_element_by_xpath("/html/body/div[2]/div[4]/div/a") #href link
time.sleep(2)
elem.send_keys(Keys.CONTROL + Keys.RETURN + "2") #open a 2nd tab again
"""Got it? find the handle, switch over the window then switch the frame"""
It is working perfectly for me. I'm open for questions...
Do this
_webDriver.SwitchTo().Window(_webDriver.WindowHandles.Where(x => x != _webDriver.CurrentWindowHandle).First());
or Last() etc.
PS there is no guarantee that the WindowHandles are in the order displayed on your browser, therefore, I would advise you keep some history of current windows before you do the command to that caused a new tab to open. Then you can compare your stored window handles with the current set and switch to the new one in the list, of which, there should only be one.
#Test
public void openTab() {
//Open tab 2 using CTRL + t keys.
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"t");
//Open URL In 2nd tab.
driver.get("http://www.qaautomated.com/p/contact.html");
//Call switchToTab() method to switch to 1st tab
switchToTab();
}
public void switchToTab() {
//Switching between tabs using CTRL + tab keys.
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"\t");
//Switch to current selected tab's content.
driver.switchTo().defaultContent();
}
we can use keyboard events and automate opening and switching between multiple tabs very easily. This example is refered from HERE
I must say i tried this as well, and while it seemingly works with some bindings (Java, as far as Jonathan says, and ruby too, apparently), with others it doesnt: selenium python bindings report just one handle per window, even if containing multiple tabs
IJavaScriptExecutor is very useful class which can manipulate HTML DOM on run time through JavaScript, below is sample code on how to open a new browser tab in Selenium through IJavaScriptExecutor:
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
object linkObj = js.ExecuteScript("var link = document.createElement('a');link.target='_blank';link.href='http://www.gmail.com';link.innerHTML='Click Me';document.getElementById('social').appendChild(link);return link");
/*IWebElement link = (IWebElement)linkObj;
link.Click();*/
browser.Click("//*[#id='social']/a[3]");
Just to give an insight, there are no methods in Selenium which would allow you to open new tab, the above code would dynamically create an anchor element and directs it open an new tab.
You can try this way, since there is action_chain in the new webdriver.
I'm using Python, so please ignore the grammar:
act = ActionChains(driver)
act.key_down(Keys.CONTROL)
act.click(link).perform()
act.key_up(Keys.CONTROL)
For MAC OS
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Firefox()
driver.get("http://google.com")
body = driver.find_element_by_tag_name("body")
body.send_keys(Keys.COMMAND + 't')
Java Robot can be used to send Ctrl+t (or Cmd+t if MAC OS X) as follows:
int vkControl = IS_OS_MAC ? KeyEvent.VK_META : KeyEvent.VK_CONTROL;
Robot robot = new Robot();
robot.keyPress(vkControl);
robot.keyPress(KeyEvent.VK_T);
robot.keyRelease(vkControl);
robot.keyRelease(KeyEvent.VK_T);
A complete running example using Chrome as browser can be forked here.
I would prefer opening a new window. Is there really a difference in opening a new window vs opening a new tab from an automated solution perspective ?
you can modify the anchors target property and once clicked the target page would open in a new window.
Then use driver.switchTo() to switch to the new window. Use it to solve your issue
Instead of opening new tab you can open new window using below code.
for(String childTab : driver.getWindowHandles())
{
driver.switchTo().window(childTab);
}

Bring the Firefox Browser to Front using selenium Java (Mac OSX)

I am using three instances of fire fox driver for automation.I need to bring current active firefox browser into front, Because I am using some robo classes for some opertation. I had tried java script alert for google chrome in mac ( same operation) and its worked fine. In windows used user32 lib. In the case of firefox mac its showing the alert in background but the web page is not come into front.
((JavascriptExecutor)this.webDriver).executeScript("alert('Test')");
this.webDriver.switchTo().alert().accept();
The above code I used for chrome in Mac. Same code is working and showing alert for firefox but the window is not coming to front.
Please suggest if there any other method for doing the same in firefox.
Store the window handle first in a variable, and then use it to go back to the window later on.
//Store the current window handle
String currentWindowHandle = this.webDriver.getWindowHandle();
//run your javascript and alert code
((JavascriptExecutor)this.webDriver).executeScript("alert('Test')");
this.webDriver.switchTo().alert().accept();
//Switch back to to the window using the handle saved earlier
this.webDriver.switchTo().window(currentWindowHandle);
Additionally, you can try to maximise the window after switching to it, which should also activate it.
this.webDriver.manage().window().maximize();
Try switching using the window name:
driver.switchTo().window("windowName");
Alternatively, you can pass a "window handle" to the switchTo().window() method. Knowing this, it’s possible to iterate over every open window like so:
for (String handle : driver.getWindowHandles()) {
driver.switchTo().window(handle);
}
Based on the Selenium documentation: http://docs.seleniumhq.org/docs/03_webdriver.jsp
As described in other topics, you can use
driver.manage().window().setPosition(new Point(-2000, 0));
too.
# notifications for selenium
chrome_options = webdriver.ChromeOptions()
prefs = {"profile.default_content_setting_values.notifications": 2}
chrome_options.add_experimental_option("prefs", prefs)
current_path = os.getcwd() # current working path
chrome_path = os.path.join(current_path, 'chromedriver')
browser = webdriver.Chrome(executable_path=chrome_path, chrome_options=chrome_options)
browser.switch_to.window(browser.current_window_handle)
browser.implicitly_wait(30)
browser.maximize_window()
browser.get("http://facebook.com")
Only thing that worked for me on mac: self.driver.fullscreen_window().

Categories