close the window popup using JS - javascript

Writng script for closing window which i get as a pop up in any website for example
if u launch www.myntra.com it gives a window like if u have facebook acount login.. am trying to close this facebook window
HTML code:
<div class="close"></div>
frist i have tried normal webdriver script
driver.findElement(By.xpath("//div[#class='close']").click;
above code gives me exception like "element is not visible you may want to interact with"
i have tried using javaexecutor somthing like below'
WebElement element = driver.findElement(By.xpath("//div[#class='close']"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", element);
above JS code doesnot give me exception but`enter code here` even it doesnot close the window for which i have written the code.
1)why in above webdriver code i get exception like "element is not visible you may want to interact with"? what is reason behind this.
2) what is the way to close the window?
i have spent whole day but dint got solution please help me out thanks in advance

You can close the browser window with Selenium, without Javascript.
// get the current windowHandle before triggering the popup (if loading myntra triggers the popup, just navigate to localhost and get the windowHandle there, before navigating to myntra)
String window1 = driver.getWindowHandle();
// trigger the popup
driver.get("www.myntra.com");
// get all window handles
String[] handles = driver.getWindowHandles().toArray(new String[2]);
// switch focus to the popup window
driver.switchTo().window(handles[handles.length - 1]);
// close the popup
driver.close();
// switch focus back to the original window
driver.switchTo().window(window1);
// continue test...

Related

browser pop up is not closing in selenium

After launching the url there is a email pop up that i am trying to close. i have written xpath and able to find the close icon with that. but when i am trying to execute it is not closing. then i added implicitly wait for the element to be visible and then trying to close. still it is not closing.
Can you please tell me what would be the reasons for such cases and how it can be solved.
and Submit button is also not clicking i have given the correct xpath.
Thanks in advance..
below is the code snippet.
public static void main(String[] args) {
WebDriver driver;
System.setProperty("webdriver.chrome.driver", "E:\\Softwares\\Chromedriver.exe");
driver = new ChromeDriver();
driver.get("https://html.com/input-type-file/");
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
WebElement closeButon = driver.findElement(By.xpath("//a[#class='om-close miami-element-close miami-close']"));
if(closeButon.isDisplayed())
{
System.out.println("close Buton is there.. ");
closeButon.click();
System.out.println("close Buton closed ");
}
driver.findElement(By.xpath("//input[#name='fileupload']")).sendKeys("E:\\Users\\laxman_p\\Desktop\\PromoFeature.txt");
//Submit button
driver.findElement(By.xpath("//*[#id='post-206']/div/div[3]/form/input[2]")).click();
}
If you cant close it by xpath,
I think this issue can be related with focused window,
You need to use getWindowHandle and switchTo methods to focus this pop-up.
After that you will be able to make process on this pop-up.
driver.getWindowHandles()
returns set of windows.
driver.switchTo.window(windowId);
will switch you to window which you want to focus on.

Why does WebDriver not move to the next page when "clicking" an element?

I am doing:
driver = new webdriver.Builder()
.forBrowser('safari')
.build();
var referrer = 'http://localhost:3000/tours/hood-river';
// console.log(referrer);
driver.get(referrer);
driver.findElement(By.id('requestGroupRate')).click();
//requestGroupRate is a link, so clicking it should move it to a new page
driver.wait(function(){
return driver.findElement(By.id('myThing')).then(function(element){
console.log("hereere");
assert(element.value === referrer);
done();
});
},10000);
I find that the findElement(By.id('myThing')), fails, even though the page it should be on clearly has 'myThing'. But if I change the line to
driver.findElement(By.id('requestGroupRate'))..
Then the element is found! This leads me to believe, that the click() does not cause the driver to navigate to the link.
EDIT: The link I am trying to click on:
<a id="requestGroupRate"
href="/tours/request-group-rate">Request Group Rate.</a>
you can simply add driver.sleep(10000) after click() for debug purpose.
if the page changed, means the link and click() worked and the possible failed reason it's when script click on the link, the page is still loading, so browser failed to response to the click event.
then you can move the driver.sleep(10000) after browser.get() to see click() can work or not.
As suggested by acdcjunior findout if element is clickable use browser developer tools. Chrome it is a side panel, Firefox it is a marker at the end of the HTML tag.
I have had issues getting Selenium to click on a GIS map. In that case i use an alternative (will need to translate this Java into Javascript):
((JavascriptExecutor) driver).executeScript("document.getElementById('map_container').dispatchEvent(new Event('click'));");
Also suggest testing your xpath in the browser developer console:
document.evaluate(".//tagName[#id='Query']", document,null, XPathResult.ANY_TYPE, null).iterateNext();
Or testing your cssSelector in the browser developer console:
document.querySelector('#idtext')

Close Flipkart open pop-up and go to main window using Selenium

WebDriver driver = new FirefoxDriver();
driver.get("https://www.flipkart.com");
driver.manage().window().maximize();
String parentWindowHandler = driver.getWindowHandle(); // Store your parent window
String subWindowHandler = null;
Set<String> handles = driver.getWindowHandles(); // get all window handles
Iterator<String> iterator = handles.iterator();
while (iterator.hasNext()){
subWindowHandler = iterator.next();
}
driver.switchTo().window(subWindowHandler);
I tried it by switching to main window also. Please add valuable input or code to close the pop up.
You can try using the java Robot API by importing java.awt.Robot libraries. An example is here:
One solution for File Upload using Java Robot API with Selenium WebDriver by Java
You can try to use it similarly to press the Esc key. Pressing Esc on flipkart website gets rid of the pop-up.
The pop-up which appears on Flipkart's website is a simple HTML modal. Window handle is used when a new pop-up window needs to be accessed.
To close the pop-up just click on the cross on the top right corner of the pop-up. Use waits to ensure that selenium finds the WebElement.
Try this:
driver.get("https://www.flipkart.com");
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement cross = wait.until(
ExpectedConditions.visibilityOfElementLocated(By.className("close-icon")));
cross.click()

closing browser within chrome page on test complete

So using TestComplete I'm essentially trying to open up a session on chrome, navigate to a web page, and then click a button on that page. after I'm finished I want to close that browser page. I'm having trouble closing the page though. Here is the code I have so far.
function ChromeTest
{
Browsers.Item(btChrome).Run(MyWebAdress);
var browser = Sys.Browser("chrome");
var page = Sys.Browser("chrome").Page(MyWebAdress);
var MyButton = page.ButtonLocation;
MyButton.click();
browser.BrowserWindow.Close(5000);
}
however, at the Close line I get an error that says "Unable to find the object BrowserWindow". Thanks in advance for any help you have.
Change BrowserWindow to BrowserWindow(0) (or whatever index you see in the Object Browser):
browser.BrowserWindow(0).Close(5000);
Or you can call Close() directly on the Chrome process:
browser.Close(5000);

I need to open a new window in the background with JavaScript, and make sure the original is still focused

I have a window I'm opening with a Javascript function:
function newwindow()
{
window.open('link.html','','width=,height=,resizable=no');
}
I need it that once the new window opens that the focus returns to the original window.
How can I do that?
And where do I put the code - in the new window, or the old one?
Thanks!
This is known as a 'pop-under' (and is generally frowned upon... but I digress).. It should give you plenty to google about
You probably want to do something like:
var popup = window.open(...);
popup.blur();
window.focus();
Which should set the focus back to the original window (untested - pinched from google). Some browsers might block this technique.
After calling window.open, you may try to use
window.resizeTo(0,0);
window.moveTo(0,window.screen.availHeight+10);
this way can not really open window in background, but works in similar way. Chrome works fine, did not try other browser.
If Albert's solution doesn't work for you and you actually want the window visible, but to be opened behind the current window, you can try opening a new tab in the opener window and closing it right away, this will bring the focus back to the opener window.
window.open('link.html','','width=,height=,resizable=no');
window.open().close();
However, I believe whether the second window opens in a tab or a new window depends on your browser settings.
Please don't use "pop-unders" for evil.
You can use either
"blur" or
"focus" to do that required action.
"blur"
function newwindow()
{
var myChild= window.open('link.html','','width=,height=,resizable=no');
myChild.blur();
}
"focus"
function newwindow()
{
window.open('link.html','','width=,height=,resizable=no');
window.focus();
}
Put the code in your parentWindow (i.e. the window in which you are now)
Both will work.
tl;dr - in 2022 - ctrl/cmd clicking on a button and window.open(url, "_blank") in a javascript button handler's for loop will open multiple tabs in the background in Chrome.
I'm looking for this as of 2022 and none of the answers here worked (here and everywhere else I looked). My use case is clicking a button in a (progressive) web app which opens deep links to items in a list in background tabs (i.e. not "for evil").
It never occurred to me that ctrl/cmd + clicking on the button would open tabs in the background, but it does just as if the user clicked on an anchor tag itself directly - but only in Chrome. Combined with Chrome's relatively recent tab grouping feature, this can be very useful inside PWAs.
const isMozilla =
window?.navigator?.userAgent?.toString().toLowerCase().includes('firefox') ?? false;
for (let index = 0; index < urls.length; index++) {
const url = isMozilla ? urls.reverse()[index] : urls[index];
window.open(url, "_blank");
}
Note: I reverse() the array on Mozilla to get the order of newly created tabs as the user would expect them.
You can just use '_self'. It will be stay to the same page an
window.open(url, '_self');

Categories