Skip to content Skip to sidebar Skip to footer

Open A Browser With Java

I hava a java program with two buttons, one for chrome and one for firefox. I press one of them, and the browser starts at some particualar location on the screen and with smalle

Solution 1:

For Windows, you can do something like this using Runtime:

Runtime rt =Runtime.getRuntime();
rt.exec("C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe stackoverflow.com");

I believe that you can do something similar for Google Chrome. I took a look to a code I implemented in the past for Chrome and it was a little different, but previous approach should work as well:

Runtimert= Runtime.getRuntime();
rt.exec(newString[]{"cmd", "/c","start chrome http://www.stackoverflow.com"});

If you would like to do it for a Linux based OS, then you can use Runtime as well:

Runtimert= Runtime.getRuntime();
rt("/usr/bin/firefox -new-window http://www.stackoverflow.com");

I remember I got some references from this page:

https://www.mkyong.com/java/open-browser-in-java-windows-or-linux/

Hope it can help you.

Solution 2:

ScriptEngineManager runs the script on server side. window is a client-side object, you can't access it from server.

in another word since you are not executing your script in a browser, the window object is not defined.

You can try this way to open a website on your default browser of the operating system:

     Desktop desktop=Desktop.getDesktop();
     URIurl=newURI("http://somewhere");
     desktop.browse(url);

to open a non-default browser in Java you should use Runtime.exec()

for Windows OS try this it worked for me:

String browserPath = "C:/Program Files/Mozilla Firefox/firefox.exe";
     String url = "http://somewhere";
     try {
             String[] b = {browserPath, url};
             Runtime.getRuntime().exec(b);
          }
      catch (Exception exc) {
              exc.printStackTrace();
      }

for further information on how to use Runtime.exec() on others OS read here

Post a Comment for "Open A Browser With Java"