2

I can open a new window with Selenium WebDriver by using Java and JavaScript. I am using Firefox. The code is as follows:

WebDriver driver = new FirefoxDriver();
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("function createDoc(){var w = window.open(); w.document.open(); w.document.write('<h1>Hello World!</h1>'); w.document.close();}; createDoc();");

How can I open a new tab in the same browser by using WebDriver (Selenium 2)?

Ripon Al Wasim
  • 36,924
  • 42
  • 155
  • 176
  • You can try this [Open url in new tab using javascript][1] [1]: http://stackoverflow.com/q/4907843 – hamon Aug 27 '12 at 09:25
  • @Hamon: I tried the following: jse.executeScript("function createDoc(url){window.open(url, '_blank');}; createDoc(this.href);"); Same thing was happened, i.e., a new window was opened instead of new tab [Note: my concern is to open new tab, NOT new window] – Ripon Al Wasim Aug 27 '12 at 09:52

4 Answers4

1

There is no standard support in JavaScript or HTML for opening a link in a tab vs a window. It's depending on browser and settings. Some browsers default to opening in new tabs (like Chrome and Safari). Some browser allows the user to configure the behavior. Bottom line, you shouldn't design your site to rely on opening new windows in tabs as there is no reliable and cross-browser compatible mechanism for doing that.

pap
  • 27,064
  • 6
  • 41
  • 46
  • That is, there is no extra/additional code for opening new tab, right am I? Is it possible to do by configuring browser set up? – Ripon Al Wasim Aug 27 '12 at 10:44
  • Some browsers allow you to specify if new windows (window.open or target="_blank") should be opened in a new window or a new tab. In Firefox you can set it under Tools->Options->Tabs, for instance. – pap Aug 27 '12 at 12:52
  • thanks. I have set up Tabs from Tools->Options->Tabs, but unfortunately Selenium 2 (WebDriver) failed to open a new tab instead of a new window – Ripon Al Wasim Aug 27 '12 at 13:00
  • Like I said, it's not predictable. I have no idea how Selenium interacts with Firefox with regards to these settings. Don't rely on consistent behavior with regards to tabs and don't design sites with expectations that it should behave one way or the other when opening new windows. – pap Aug 27 '12 at 14:43
1

Wasim,

cdriver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"t");

You can use above line to open new tab in a same browser (Works in Firefox)

Ripon Al Wasim
  • 36,924
  • 42
  • 155
  • 176
Suresh
  • 26
  • 1
0

It is mostly depends on your browser settings and there is no separate methods for opening link in new window or new tab

Dhivya
  • 689
  • 8
  • 14
-1

It also depends on how your browser is configured to open pop-up's.

hamon
  • 1,006
  • 6
  • 7