1

So I've recently wrote code:

Runtime r = Runtime.getRuntime(); 
    Process p = null; 
    try 
    {
        p = r.exec("firefox"); 
        p.waitFor(); 
    } catch (Exception e) 
    {
        System.out.println("Error executing app");
    }

And I was wondering if there is a way to for example force the browser not just to open but execute certain commands or just open a link. How do I do that?

2
  • 1
    The firefox command can take a command line argument indicating the URL to go to. I'm not sure what "execute certain commands" means, but if you're looking to perform actions on a webpage, you want a web driver like Selenium (Selenium was originally written in Python, but based on the website it looks like they have a Java version) Commented Jul 15, 2022 at 19:10
  • Do you want to open the browser from executable or default browser? Commented Jul 15, 2022 at 19:13

1 Answer 1

1

If you want to open the default browser with an URL provided you can use this function. java.awt.Desktop is suitable for windows and xdg-open opens a file or URL in the user's preferred application in linux environment. If a URL is provided the URL will be opened in the default web browser.

    public void openDefaultBrowser(URI uri) throws BrowserException {
        if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
            // windows
            Desktop desktop = Desktop.getDesktop();
            try {
                desktop.browse(uri);
            } catch (IOException e) {
                throw new BrowserException(e.getLocalizedMessage());
            }
        } else {
            // linux / mac
            Runtime runtime = Runtime.getRuntime();
            try {
                runtime.exec("xdg-open " + uri.toString());
            } catch (IOException e) {
                throw new BrowserException(e.getLocalizedMessage());
            }
        }
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.