Close browser window using java code

橙三吉。 提交于 2019-12-20 05:25:29

问题


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

回答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




回答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.



来源:https://stackoverflow.com/questions/29842930/close-browser-window-using-java-code

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!