Close browser window using java code

后端 未结 3 990
离开以前
离开以前 2021-01-25 02:23

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

相关标签:
3条回答
  • 2021-01-25 03:06

    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

    0 讨论(0)
  • 2021-01-25 03:08

    Use the below code snippet

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

    change the name of the browser according to your needs.

    0 讨论(0)
  • 2021-01-25 03:13

    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.

    0 讨论(0)
提交回复
热议问题