我应该如何使用 java 代码关闭打开的浏览器窗口。我找到了一种方法来首先找到该过程然后结束该过程。有没有更好的办法?我最初使用以下代码打开了浏览器。我在 CentOS 工作。
String url = "http://192.168.40.174/test15.html";
Runtime runtime = Runtime.getRuntime();
runtime.exec("/usr/bin/firefox -new-window " + url);
我应该如何使用 java 代码关闭打开的浏览器窗口。我找到了一种方法来首先找到该过程然后结束该过程。有没有更好的办法?我最初使用以下代码打开了浏览器。我在 CentOS 工作。
String url = "http://192.168.40.174/test15.html";
Runtime runtime = Runtime.getRuntime();
runtime.exec("/usr/bin/firefox -new-window " + url);
我试图实现类似的事情,而不太关心会打开哪个浏览器。我遇到了一个基于 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();
}
}
当然,如果您以这种方式调用 close()
,您将不会真正看到嵌入的浏览器窗口。它应该在代码的另一部分调用,例如响应按钮按下。
你可以把它放在
Process
中并杀死它。您应该使用 String 数组执行命令
这不太容易出错: Java execute a command with a space in the pathname
或者使用
ProcessBuilder
: ProcessBuilder Documentation