Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open URL in existing browser/tab in java

With the following Code I managed to open an URL with my external Browser (in my case - Firefox). Every URL open action creates a new tab and over time I have hundreds of tabs, which I want to prevent. I use this for a tool to visually check some dates in a webpage and when pressing next, it should show the next page in the same tab.

How do i achieve this ?

Code:

public static void openWebpage(URL url) {
    try {
        openWebpage(url.toURI());
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }
}

public static void openWebpage(URI uri) {
    Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null;
    if (desktop != null && desktop.isSupported(Desktop.Action.BROWSE)) {
        try {
            desktop.browse(uri);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
like image 369
mcfly soft Avatar asked Oct 17 '14 06:10

mcfly soft


Video Answer


1 Answers

I think you need to use a WebDriver for this, but maybe thats a little bit of overkill:

http://docs.seleniumhq.org/docs/03_webdriver.jsp

Samplecode:

driver = new FirefoxDriver();
driver.get("http://google.com");
driver.navigate().to("http://stackoverflow.com");

the last line will use the same window to open the new url.

like image 187
Ahmed Hasn. Avatar answered Oct 02 '22 23:10

Ahmed Hasn.