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 brows
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
Use the below code snippet
Runtime runtime = Runtime.getRuntime();
runtime.exec("killall -9 firefox");
change the name of the browser according to your needs.
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.