I want the chrome driver instance created in main method to be used in the method handlecase

public static void main (String args[]) throws IOException, OpenXML4JException {
             
            System.setProperty("webdriver.chrome.driver", "C:\\Users\\sample\\Downloads\\chromedriver-win64\\chromedriver.exe");
            ChromeOptions options = new ChromeOptions();
            static WebDriver driver=new ChromeDriver(options);
            options.addArguments("user-data-dir=/Users/sample/Library/Application Support/Google/Chrome/")
            driver.manage().window().maximize();
}

public static void handlecase(String type) {
        
        for (i=0; i<num; i++) { 
            driver.get(type);
}
}

Here we get the error as driver cannot be resolved.

I tried this workaround

public class criteria {
        static ChromeOptions options = new ChromeOptions();     
        static WebDriver driver=new ChromeDriver(options);

public static void main (String args[]) throws IOException, OpenXML4JException {
             
        System.setProperty("webdriver.chrome.driver", "C:\\Users\\sample\\Downloads\\chromedriver-win64\\chromedriver.exe");
        options.addArguments("user-data-dir=/Users/sample/Library/Application Support/Google/Chrome/")
        driver.manage().window().maximize();
}

public static void handlecase(String type) {
        
        for (i=0; i<num; i++) { 
            driver.get(type);
}
}


It worked but the problem is that it creates a new session and i cant use my cookies here.

1

There are 1 answers

0
NeuronB On

You get "driver cannot be resolved" error because the "handlecase" method doesn't know what "driver" is. Read this to learn about variable scopes in Java.

The workaround you posted doesn't throw this because here the variable "driver" is a static variable belonging to the "criteria" class and can be accessed by all it's methods. As to why it is creating a new session, not enough information is available. Please post how you call the "handleclass" method if you are interested in an answer to this.