0

I have created a function to get Chrome browser path for both windows and OS.

private static String getChromeBinaryPath() {
    String os = System.getProperty("os.name").toLowerCase();
    if (os.contains("win")) {
        return "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe";
    } else if (os.contains("mac")) {
        return "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome";
    }
    throw new IllegalStateException("Unsupported operating system: " + os);
}

Is there a way, that instead of defining a statically, it will be more dynamic

  • You can try to use https://bonigarcia.dev/webdrivermanager/ instead of local webdrivers – Areke Jun 28 '23 at 11:50

1 Answers1

0

Yes, you can make your function more dynamic by allowing it to search for the Chrome browser executable in different locations based on the operating system like below.

private static String getChromeBinaryPath() {
    String os = System.getProperty("os.name").toLowerCase();
    String chromeBinaryPath = null;
    
    if (os.contains("win")) {
        chromeBinaryPath = searchChromeBinaryInWindows();
    } else if (os.contains("mac")) {
        chromeBinaryPath = searchChromeBinaryInMac();
    }
    
    if (chromeBinaryPath == null) {
        throw new IllegalStateException("Chrome browser path not found for the current operating system: " + os);
    }
    
    return chromeBinaryPath;
}

private static String searchChromeBinaryInWindows() {
    // Possible locations to search for Chrome on Windows
    String[] possiblePaths = {
        "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
        "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"
    };

    for (String path : possiblePaths) {
        File file = new File(path);
        if (file.exists()) {
            return path;
        }
    }

    return null; // Chrome not found
}

private static String searchChromeBinaryInMac() {
    // Possible locations to search for Chrome on macOS
    String[] possiblePaths = {
        "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
        "/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary"
    };

    for (String path : possiblePaths) {
        File file = new File(path);
        if (file.exists()) {
            return path;
        }
    }

    return null; // Chrome not found
}

Hope this helps!!