1

How should i close an opened browser window using java code. I have found a way to first find the process then end that process. Is there any better way? I have opened the browser initially using the below code. I am working in CentOS.

String url = "http://192.168.40.174/test15.html";
Runtime runtime = Runtime.getRuntime();
runtime.exec("/usr/bin/firefox -new-window " + url);
Pink Giraffe
  • 29
  • 1
  • 1
  • 5

3 Answers3

0

Use the below code snippet

Runtime runtime = Runtime.getRuntime();
runtime.exec("killall -9  firefox");

change the name of the browser according to your needs.

thepunitsingh
  • 713
  • 1
  • 12
  • 30
-1

You can put it in a Process and kill that.

Runtime runtime = Runtime.getRuntime();
Process p = runtime.exec("/usr/bin/firefox -new-window " + url);
p.destroy();

-- update --

You should execute your command with a String array

Process p = Runtime.getRuntime().exec(new String[]{
    "/usr/bin/firefox",
    "-new-window", url
});

This is less prone to errors: Java execute a command with a space in the pathname

Or use ProcessBuilder: ProcessBuilder Documentation

Community
  • 1
  • 1
Jelle de Fries
  • 885
  • 1
  • 11
  • 20
  • 2
    Note that if the user opened additional windows while in that browser, all the windows will end up being destroyed, not just one. – RealSkeptic Apr 24 '15 at 09:14
  • @Jelle ..tx for your answer but using runtime its takes alot of time to open the browser so now i am using the belwo code to open browser. in this case what could be a appropriate way to close the opened browser other than finding the process and then closing it.Any suggestion ? Desktop dt = Desktop.getDesktop(); //dt.browse( new URI(url) ); – Pink Giraffe Apr 28 '15 at 06:53
  • @PinkGiraffe Not that I know of. Maybe you should find out why your `Runtime` is acting slow. – Jelle de Fries Apr 28 '15 at 07:36
-2

I was trying to achieve a similar thing, without caring too much which browser will open. I come accross a solution based on Java FX:

public class MyBrowser extends Application {

private String url = "http://stackoverflow.com/questions/29842930/close-browser-window-using-java-code";

public static void main(String[] args) {
    launch(args);
}

@Override
public void start(Stage stage) throws Exception {

    WebView webview = new WebView();
    webview.getEngine().load(url);
    webview.setPrefSize(1800, 1000);

    stage.setScene(new Scene(webview));
    stage.show();

    //stage.close();

}

}

Of course if you call close() this way, you will not really see the embedded browser window. It should be called in another part of the code, e.g. in response to a button push.

ynka
  • 1,457
  • 1
  • 11
  • 27