Open URL in existing browser/tab in java

2019-06-16 05:11发布

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();
        }
    }
}

1条回答
Explosion°爆炸
2楼-- · 2019-06-16 05:39

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.

查看更多
登录 后发表回答