How to print the page and close the Print window in selenium - javascript

Selenium fresher:
I used the following code in selenium to open the print window but it doesn't work
Keyboard keyboard = ((HasInputDevices)driver).getKeyboard();
keyboard.pressKey(Keys.ENTER);
keyboard.pressKey(Keys.chord(Keys.CONTROL, "p"));
And i used the following code to open the Print window and it works
((JavascriptExecutor) driver).executeScript("print()");
My Question is how to print the page and close the print window?

You can use the kiosk-printing chrome option to complete the print without interacting with print window.
Here is the snippet that you can use.
Java:
ChromeOptions options = new ChromeOptions();
options.addArguments("--kiosk-printing");
WebDriver driver = new ChromeDriver(options);
driver.get("https://google.com");
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.print();");
Python:
options = webdriver.ChromeOptions()
options.add_argument('--kiosk-printing')
driver = webdriver.Chrome(chrome_options=options)
driver.get("https://google.com")
driver.execute_script('window.print();')
You will see the print window for a fraction of seconds and then it will close automatically. Then you can see the printing job in your default printer.

Related

Removing scrollbar from Selenium Screenshots

I'm getting screenshots of webpages using Chromedriver. My code works well.
I'm now attempting to remove the ugly scrollbars. Would it be possible to inject CSS into the page? I have seen a couple of similar questions, which do hint that this is possible ("You can also make Chromedriver open the url in a popup without scrollbars. You can do this using some Javascript.") but doesn't show how this is possible.
Has anybody got any idea as to how to do this?
IWebDriver driver = new ChromeDriver();
driver.Manage().Window.Size = new Size(1100, 1100);
driver.Navigate().GoToUrl("http://google.com/");
Screenshot ss = ((ITakesScreenshot)driver).GetScreenshot();
//Temp Img
string screenshot = ss.AsBase64EncodedString;
byte[] screenshotAsByteArray = ss.AsByteArray;
ss.SaveAsFile(fileNameTemp, ScreenshotImageFormat.Jpeg);
ss.ToString();
// Create a driver instance for chromedriver
IWebDriver driver = new ChromeDriver();
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
driver.Manage().Window.Size = new Size(1100, 1100);
driver.Navigate().GoToUrl(hehe[i]);
js.ExecuteScript("return document.body.style.overflow = 'hidden';");
This worked!

How to handle a new window in selenium when I opened it by javascript

Using selenium in internet explorer I have opened a new window with javascript code:
((JavascriptExecutor) driver).executeScript("windows.open('www.google.com')");
When I try to move to that new window selenium does not detect the window. At the time of printing the number of windows opened by the driver I only get 1:
Set<String> handlesSet = visor.getWindowHandles();
List<String> handlesList = new ArrayList<String>(handlesSet);
System.out.println("open windows: " + handlesList.size());
My question: ¿Is it possible to manage that new window opened from javascript?
Thank you.
It doesn't work because windows, it should window, without s:
((JavascriptExecutor) driver).executeScript("window.open('https://www.google.com')");
Don't forget to put full url with https://

Opening a new tab using Ctrl + click combination in Selenium Webdriver

I am attempting to use ctrl + click on a link to open it in a new tab. This is working fine in Chrome 58. Please find the code below:
action.keyDown(Keys.CONTROL).click(driver.findElement(By.xpath
("//section[#class='filmStrip__basic']//a[text()='En savoir
plus']"))).keyUp(Keys.CONTROL).build().perform();
I am using the same code on IE, Firefox and Safari but getting the following error:
Firefox 54: The link is getting open in the same tab.
IE 11: Nothing happening.. the control is moving to the next line
Safari: exception on action.keyDown-Unrecognized command
Help related to any one browser is also appreciated.
Thanks
As you are trying to click on a link which is within a <a> tag, instead of xpath you can use the linkText locator. Here is the sample code with opens the url http://www.google.com, verifies the Page Title, uses Actions class to click on the Gmail link to open https://accounts.google.com in a new tab.
String URL="http://www.google.com";
System.setProperty("webdriver.gecko.driver", "C:\\Utility\\BrowserDrivers\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get(URL);
System.out.println("Page Title is : "+driver.getTitle());
WebElement link = driver.findElement(By.linkText("Gmail"));
Actions newTab = new Actions(driver);
newTab.keyDown(Keys.CONTROL).click(link).keyUp(Keys.CONTROL).build().perform();
You can find a relevant Python based solution in How to open a link embed in web element in the main tab, in a new tab of the same window using Selenium Webdriver
Another way is to use javascript executor:
JavascriptExecutor jse = (JavascriptExecutor) driver;
jse.executeScript("window.open('','_blank');");
As for your problem I had it too and didn't find anything usefull until I found this workaround.
I even tried: solution with ctrl + enter
try this way....
// specify chromedriver.exe directory path and replace in "driverPath"
String driverPath = "C:/Users......";
WebDriver driver;
System.setProperty("webdriver.chrome.driver", driverPath + "chromedriver.exe");
driver = new ChromeDriver();
System.out.println("lanuching 1st url in tab1");
driver.navigate().to(
"https://amazon.com");
System.out.println("lanuched 1st url in tab1");
Thread.sleep(30000);
((JavascriptExecutor) driver).executeScript(
"window.open('http://ebay.com');");
Thread.sleep(20000);
Set<String> allwh = driver.getWindowHandles();
System.out.println(allwh.size());
for (String v : allwh) {
System.out.println(v);
driver.switchTo().window(v);
String title = driver.getTitle();
System.out.println("2nd url in tab2" + title);

Java Selenium, storing updated page source after javascript activation

I have managed to open a browser with my link and activate the javascript, which allows the page to display more results. Once this is done I am trying to print the new updated page source in the console but all it shows is the original source prior to the javascript activation. My code so far is shown below.
WebDriver driver = new FirefoxDriver();
driver.get("www.desiredLink.com");
if (driver instanceof JavascriptExecutor)
{
((JavascriptExecutor)driver).executeScript("javascriptFunction();");
System.out.println(driver.getPageSource());
}
else
{
throw new IllegalStateException("No support for JavaScript!");
}
You have to get attribute "innerHTML" of body instead of pageSource:
String bodyHtml = driver.findElement(By.tagName("body")).getAttribute("innerHTML");

Disable Javascript in Selenium? Noscript doesn't seem to work

I am trying to disable javascript in selenium using noscript extension, as suggested here -->How to disable Javascript when using Selenium by JAVA?
But, it looks like it no longer works,
Here is what I have written :
FirefoxProfile profile = new FirefoxProfile();
File extPath = new File("noscript.xpi");
profile.addExtension(extPath);
//profile.setPreference("javascript.enabled", false);
WebDriver driver = new FirefoxDriver(profile);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get("http://enable-javascript.com");
Even tried it by loading a profile that has javascript disabled, that doesn't seem to work either.
Code :
File profileDirectory = new File("Profiles/4hsi6txm.testing");
FirefoxProfile profile = new FirefoxProfile(profileDirectory);
DesiredCapabilities cap = DesiredCapabilities.firefox();
//
cap.setCapability(FirefoxDriver.PROFILE, profile);
WebDriver driver = new FirefoxDriver(cap);
driver.get("http://enable-javascript.com");
I am trying it on Firefox version-43.0.1 and selenium version-2.48.2
Any fix for this ?
Thanks :)

Categories