如何使用java代码关闭打开的浏览器窗口。我已经找到了一种方法,首先找到进程,然后结束该进程。有没有更好的办法?我最初使用下面的代码打开了浏览器。我在CentOS工作。
String url = "http://192.168.40.174/test15.html";
Runtime runtime = Runtime.getRuntime();
runtime.exec("/usr/bin/firefox -new-window " + url);
发布于 2020-12-24 21:22:40
使用下面的代码片段
Runtime runtime = Runtime.getRuntime();
runtime.exec("killall -9 firefox");
根据需要更改浏览器的名称。
发布于 2015-04-24 17:05:04
你可以把它放在Process
里,然后把它杀了。
Runtime runtime = Runtime.getRuntime();
Process p = runtime.exec("/usr/bin/firefox -new-window " + url);
p.destroy();
-更新--
您应该使用字符串数组执行命令
Process p = Runtime.getRuntime().exec(new String[]{
"/usr/bin/firefox",
"-new-window", url
});
这就不容易出错了:Java execute a command with a space in the pathname
或者使用ProcessBuilder
:ProcessBuilder Documentation
发布于 2016-08-02 22:56:20
我正在尝试实现类似的事情,而不是太在意哪个浏览器会打开。我遇到了一个基于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()
,您将不会真正看到嵌入式浏览器窗口。它应该在代码的另一部分中调用,例如响应按钮按下。
https://stackoverflow.com/questions/29842930
复制相似问题