140

Can someone point me in the right direction on how to open the default web browser and set the page to "www.example.com" thanks

Dreamspace President
  • 1,060
  • 13
  • 33
dwayne
  • 1,587
  • 3
  • 11
  • 5
  • 2
    Duplicate question: http://stackoverflow.com/q/10967451/873282 – koppor Jun 21 '15 at 12:05
  • 1
    Possible duplicate of [Getting java gui to open a webpage in web browser](http://stackoverflow.com/questions/602032/getting-java-gui-to-open-a-webpage-in-web-browser) – Nathan Nov 09 '15 at 21:59

12 Answers12

204

java.awt.Desktop is the class you're looking for.

import java.awt.Desktop;
import java.net.URI;

// ...

if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
    Desktop.getDesktop().browse(new URI("http://www.example.com"));
}
Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
  • 3
    is this a cross-platform solution or Windows only? other answers in this thread suggest to use the Runtime class for Linux – isapir Oct 23 '13 at 04:05
  • @lgal, it worked for me on both Windows 7 and Linux (Ubuntu 10.10). It always open the default system browser (IE on Win7 and Firefox on Ubuntu, in my case) – Joaquim Oliveira Feb 18 '14 at 19:44
  • 2
    This doesnt't work for me. IsDesktopSupported method always returns false on my windows machine. What's the matter? – krzysiek.ste Mar 02 '15 at 09:29
  • 2
    If the user has assigned a custom "open with" action to the file exten like "html" then this will NOT open the browser, but the program the user has linked it with.... This is not a solution at all! – thesaint May 07 '15 at 20:12
  • Works for me in Windows7 –  Apr 27 '16 at 15:13
  • 4
    @krzysiek.ste use the `Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)` check instead. – Thibstars Jul 24 '17 at 08:30
  • Are there any resources which need to be cleared? When I do this, I´m not able to delete the corresponding .jar file as long as the browser window is open. – Franz Deschler May 25 '18 at 12:34
  • 5
    @thesaint If the user has changed the handler for html files, then that is what the user wants the default browser for html files to be, so it's just what the question was asking for. – toolforger May 10 '19 at 07:30
51

For me solution with Desktop.isDesktopSupported() doesn't work (windows 7 and ubuntu). Please try this to open browser from java code:

Windows:

Runtime rt = Runtime.getRuntime();
String url = "http://stackoverflow.com";
rt.exec("rundll32 url.dll,FileProtocolHandler " + url);

Mac

Runtime rt = Runtime.getRuntime();
String url = "http://stackoverflow.com";
rt.exec("open " + url);

Linux:

Runtime rt = Runtime.getRuntime();
String url = "http://stackoverflow.com";
String[] browsers = { "google-chrome", "firefox", "mozilla", "epiphany", "konqueror",
                                 "netscape", "opera", "links", "lynx" };
 
StringBuffer cmd = new StringBuffer();
for (int i = 0; i < browsers.length; i++)
    if(i == 0)
        cmd.append(String.format(    "%s \"%s\"", browsers[i], url));
    else
        cmd.append(String.format(" || %s \"%s\"", browsers[i], url)); 
    // If the first didn't work, try the next browser and so on

rt.exec(new String[] { "sh", "-c", cmd.toString() });

If you want to have multiplatform application, you need to add operation system checking(for example):

String os = System.getProperty("os.name").toLowerCase();

Windows:

os.indexOf("win") >= 0

Mac:

os.indexOf("mac") >= 0

Linux:

os.indexOf("nix") >=0 || os.indexOf("nux") >=0
krzysiek.ste
  • 2,246
  • 1
  • 26
  • 24
  • 1
    Why using StringBuffer here? – Stephan Aug 13 '17 at 18:52
  • 7
    Listing all the browsers in the Linux solution is very bad. What if one uses other browser than any from the list? (there's no chrome nor chromium on the list) Or has both Epiphany and Firefox, but prefers to use the latter? Using `xdg-open` is much better in this case. The solution could be therefore as simple as the macOS one. – m4tx Dec 25 '17 at 18:51
  • 1
    Another option for Windows is rt.exec("start \"" + url +"\"); – Ivan Nikitin Aug 10 '18 at 11:20
44

Here is my code. It'll open given url in default browser (cross platform solution).

import java.awt.Desktop;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

public class Browser {
    public static void main(String[] args) {
        String url = "http://www.google.com";

        if(Desktop.isDesktopSupported()){
            Desktop desktop = Desktop.getDesktop();
            try {
                desktop.browse(new URI(url));
            } catch (IOException | URISyntaxException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }else{
            Runtime runtime = Runtime.getRuntime();
            try {
                runtime.exec("xdg-open " + url);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}
Brajesh Kumar
  • 929
  • 6
  • 16
  • 2
    "'xdg-open' is not recognized as an internal or external command, operable program or batch file." – xehpuk Feb 22 '15 at 21:44
  • 11
    Thats a unix command. what are you doing running it in windows – Zuko Oct 12 '15 at 10:20
  • 8
    Along with 'Desktop.isDesktopSupported()' also check 'Desktop.getDesktop().isSupported(Action.BROWSE)'. – Kanchu Aug 15 '16 at 19:41
7

As noted in the answer provided by Tim Cooper, java.awt.Desktop has provided this capability since Java version 6 (1.6), but with the following caveat:

Use the isDesktopSupported() method to determine whether the Desktop API is available. On the Solaris Operating System and the Linux platform, this API is dependent on Gnome libraries. If those libraries are unavailable, this method will return false.

For platforms which do not support or provide java.awt.Desktop, look into the BrowserLauncher2 project. It is derived and somewhat updated from the BrowserLauncher class originally written and released by Eric Albert. I used the original BrowserLauncher class successfully in a multi-platform Java application which ran locally with a web browser interface in the early 2000s.

Note that BrowserLauncher2 is licensed under the GNU Lesser General Public License. If that license is unacceptable, look for a copy of the original BrowserLauncher which has a very liberal license:

This code is Copyright 1999-2001 by Eric Albert (ejalbert@cs.stanford.edu) and may be redistributed or modified in any form without restrictions as long as the portion of this comment from this paragraph through the end of the comment is not removed. The author requests that he be notified of any application, applet, or other binary that makes use of this code, but that's more out of curiosity than anything and is not required. This software includes no warranty. The author is not repsonsible for any loss of data or functionality or any adverse or unexpected effects of using this software.

Credits: Steven Spencer, JavaWorld magazine (Java Tip 66) Thanks also to Ron B. Yeh, Eric Shapiro, Ben Engber, Paul Teitlebaum, Andrea Cantatore, Larry Barowski, Trevor Bedzek, Frank Miedrich, and Ron Rabakukk

Projects other than BrowserLauncher2 may have also updated the original BrowserLauncher to account for changes in browser and default system security settings since 2001.

Ned
  • 937
  • 6
  • 10
  • The maintained fork of BrowserLauncher2 is available at https://github.com/rajing/browserlauncher2 – koppor Jun 21 '15 at 12:04
  • 1
    For those looking to use BrowserLauncher2 on Macs, neither the original BrowserLauncher2 or the fork mentioned by @koppor work with Mac OS X Sierra. Both assume the existence of an "mrj.version" system property which apparently no longer exists. The code will throw a NullPointerException when the launcher is constructed. See https://sourceforge.net/p/browserlaunch2/bugs/14/ for additional information. – Coren Jul 20 '17 at 05:28
6

You can also use the Runtime to create a cross platform solution:

import java.awt.Desktop;
import java.net.URI;

public class App {

    public static void main(String[] args) throws Exception {
        String url = "http://stackoverflow.com";

        if (Desktop.isDesktopSupported()) {
            // Windows
            Desktop.getDesktop().browse(new URI(url));
        } else {
            // Ubuntu
            Runtime runtime = Runtime.getRuntime();
            runtime.exec("/usr/bin/firefox -new-window " + url);
        }
    }
}
Benny Code
  • 51,456
  • 28
  • 233
  • 198
  • 6
    `/usr/bin/firefox` is not the standard browser name on non-Windows platforms! It could be Chrome, or Epiphany, or a multitude of other browsers. – toolforger Feb 03 '21 at 08:32
6

Hope you don't mind but I cobbled together all the helpful stuff, from above, and came up with a complete class ready for testing...

import java.awt.Desktop;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

public class MultiBrowPop {

    public static void main(String[] args) {
        OUT("\nWelcome to Multi Brow Pop.\nThis aims to popup a browsers in multiple operating systems.\nGood luck!\n");

        String url = "http://www.birdfolk.co.uk/cricmob";
        OUT("We're going to this page: "+ url);

        String myOS = System.getProperty("os.name").toLowerCase();
        OUT("(Your operating system is: "+ myOS +")\n");

        try {
            if(Desktop.isDesktopSupported()) { // Probably Windows
                OUT(" -- Going with Desktop.browse ...");
                Desktop desktop = Desktop.getDesktop();
                desktop.browse(new URI(url));
            } else { // Definitely Non-windows
                Runtime runtime = Runtime.getRuntime();
                if(myOS.contains("mac")) { // Apples
                    OUT(" -- Going on Apple with 'open'...");
                    runtime.exec("open " + url);
                } 
                else if(myOS.contains("nix") || myOS.contains("nux")) { // Linux flavours 
                    OUT(" -- Going on Linux with 'xdg-open'...");
                    runtime.exec("xdg-open " + url);
                }
                else 
                    OUT("I was unable/unwilling to launch a browser in your OS :( #SadFace");
            }
            OUT("\nThings have finished.\nI hope you're OK.");
        }
        catch(IOException | URISyntaxException eek) {
            OUT("**Stuff wrongly: "+ eek.getMessage());
        }
    }

    private static void OUT(String str) {
        System.out.println(str);
    }
}
Dave
  • 3,093
  • 35
  • 32
5

Its very simple just write below code:

String s = "http://www.google.com";
Desktop desktop = Desktop.getDesktop();
desktop.browse(URI.create(s));

or if you don't want to load URL then just write your browser name into string values like,

String s = "chrome";
Desktop desktop = Desktop.getDesktop();
desktop.browse(URI.create(s));

it will open browser automatically with empty URL after executing a program

2

I recast Brajesh Kumar's answer above into Clojure as follows:

(defn open-browser 
  "Open a new browser (window or tab) viewing the document at this `uri`."
  [uri]
  (if (java.awt.Desktop/isDesktopSupported)
    (let [desktop (java.awt.Desktop/getDesktop)]
      (.browse desktop (java.net.URI. uri)))
    (let [rt (java.lang.Runtime/getRuntime)]
      (.exec rt (str "xdg-open " uri)))))

in case it's useful to anyone.

Simon Brooke
  • 162
  • 2
  • 8
1

on windows invoke "cmd /k start http://www.example.com" Infact you can always invoke "default" programs using the start command. For ex start abc.mp3 will invoke the default mp3 player and load the requested mp3 file.

d-live
  • 7,926
  • 3
  • 22
  • 16
  • You already posted the portable version. I just proposed *another* solution which could be kept in mind if its not just the urls you need to open in default programs. – d-live Mar 07 '11 at 22:58
1

JavaFX bundles a cross-platform solution inside its StandaloneHostService that is independent of AWT, which is somehow similar to krzysiek.ste's answer.

I rewrote it to include some xdg-open alternatives (which are actually used by xdg-open by the way).

private static final String[][] commands = new String[][]{
        {"xdg-open", "$1"},
        {"gio", "open", "$1"},
        {"gvfs-open", "$1"},
        {"gnome-open", "$1"},  // Gnome
        {"mate-open", "$1"},  // Mate
        {"exo-open", "$1"},  // Xfce
        {"enlightenment_open", "$1"},  // Enlightenment
        {"gdbus", "call", "--session", "--dest", "org.freedesktop.portal.Desktop",
            "--object-path", "/org/freedesktop/portal/desktop",
            "--method", "org.freedesktop.portal.OpenURI.OpenURI",
            "", "$1", "{}"},  // Flatpak
        {"open", "$1"},  // Mac OS fallback
        {"rundll32", "url.dll,FileProtocolHandler", "$1"},  // Windows fallback
};

Here is the final Java snippet, avoiding string concatenation and escape character issues.

public static void showDocument(final String uri) {
    String osName = System.getProperty("os.name");
    try {
        if (osName.startsWith("Mac OS")) {
            Runtime.getRuntime().exec(new String[]{"open", uri});
        } else if (osName.startsWith("Windows")) {
            Runtime.getRuntime().exec(new String[]{"rundll32", "url.dll,FileProtocolHandler", uri});
        } else { //assume Unix or Linux
            new Thread(() -> {
                try {
                    for (String[] browser : commands) {
                        try {
                            String[] command = new String[browser.length];
                            for (int i = 0; i < browser.length; i++)
                                if (browser[i].equals("$1"))
                                    command[i] = uri;
                                else
                                    command[i] = browser[i];
                            if (Runtime.getRuntime().exec(command).waitFor() == 0)
                                return;
                        } catch (IOException ignored) {
                        }
                    }
                    String browsers = System.getenv("BROWSER") == null ? "x-www-browser:firefox:iceweasel:seamonkey:mozilla:" +
                            "epiphany:konqueror:chromium:chromium-browser:google-chrome:" +
                            "www-browser:links2:elinks:links:lynx:w3m" : System.getenv("BROWSER");
                    for (String browser : browsers.split(":")) {
                        try {
                            Runtime.getRuntime().exec(new String[]{browser, uri});
                            return;
                        } catch (IOException ignored) {
                        }
                    }
                } catch (Exception ignored) {
                }
            }).start();
        }
    } catch (Exception e) {
        // should not happen
        // dump stack for debug purpose
        e.printStackTrace();
    }
}
Kana
  • 186
  • 1
  • 2
  • 3
1

There is also

BrowserUtil.browse(uri);

(source code) that seems to be a more compatible with some more exotic setups. I recently had a client where Desktop.getDesktop().browse(uri) was failing in Fedora Linux, but BrowserUtil.browse(uri) worked.

I also believe this is now the preferred way by JetBrains to open a browser (for example, see this thread)

David Veszelovszki
  • 2,574
  • 1
  • 24
  • 23
0

As I had this same problem and found no decent solution for our case so I ported the https://www.npmjs.com/package/open npm package to Java https://github.com/vaadin/open and released it into Maven central. Can be used as

<dependency>
    <groupId>com.vaadin</groupId>
    <artifactId>open</artifactId>
    <version>8.4.0.2</version>
</dependency>
Open.open("https://stackoverflow.com/")

or for a specific browser

Open.open("https://stackoverflow.com/", App.FIREFOX);
Artur Signell
  • 1,694
  • 9
  • 9