Software Quality Assurance & Testing Stack Exchange is a question and answer site for software quality control experts, automation engineers, and software testers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

This has been asked a million times on the web, but there's no clear cut answer. I tried "-browserSessionReuse" today without any luck; my tests keep spawning new browser windows.

X:\QA\Automation\SELENIUM_SERVER>java -jar selenium-server-standalone-2.8.0.jar -log "log.txt" -browserSessionReuse -forcedBrowserMode "*googlechrome"
<snip>
13:42:25.923 INFO - Will recycle browser sessions when possible.

Maybe it's how I'm starting Selenium in my .py files?

sel = selenium('localhost', 4444, "*chrome", 'http://server/')
sel.start()

...perhaps I'm doing too many server starts?

Thanks.

share|improve this question
    
I don't think that's possible. afaik Selenium always uses new Window – Tarun Oct 19 '11 at 3:21
    
I've had the same result, and I wanted reuse at one point to check cookie values in a site test. – MichaelF Oct 19 '11 at 12:51
up vote 13 down vote accepted

This is possible with Selenium 2 and WebDriver. I'm not sure if it is with different versions. In Selenium 2 with WebDriver you can call webDriver = new FirefoxDriver() which spawns a browser, and that browser will stay open for the duration of your testing, or you can choose to close it with webDriver.Quit().
I like to close my browser window between tests so that I know my tests aren't "dirty" with stored session data that could affect how the tests run, but I can see value in some targeted tests, where I want to try a couple different scenarios while keeping the same session going.

share|improve this answer
    
Funny, I was just reading about this this morning, and I think it will solve my browser windows problem. Thank you. – Aaron Oct 19 '11 at 18:19

I have done it in the past by declaring my Selenium driver instance as a static member loaded by the entire test suite. Then, pass that member as an argument to each test. Then, I also created some methods to keep track of how many windows are open and make sure that the last window is never closed. Then, after each test I close all windows except for the last one and redirect the last window to "about:blank". Then, as my tests run, it reuses the windows.

I have since then, abandoned this method because I no longer need it, for the following reasons:

  1. Using a static global webdriver object was bad programming practice. My driver was part of a Utility class extended by all tests and therefore my test classes could not extend any other class. You can get around this my using Scala and/or JDK1.8 because they have the "defender method" interface feature, but since I am using JDK1.7, I needed to do this the right way.
  2. Now I close the browser after each test but since I now use "Selenium Grid" I dont need to worry about the performance impact of re-opening browsers anymore because I can throw more hardware at the problem and run multi-threaded.

NOTE: Here is my example of how I do things now but keep in mind that there are now better ways of doing this.

share|improve this answer

You can achieve it by using same selenium instance in multiple test. That requires some code design that controls start and stop selenium. We are using ISFW that provides a way using java so that's for sure it is possible with some efforts in python as well.

share|improve this answer

This worked for me in webdriver.io

var webdriverio = require('webdriverjs-angular');
var options = {
    desiredCapabilities: {
        browserName: 'firefox'
    },
    ngRoot: 'html' // main application selector
};

var wd = webdriverio.remote(options).init();

var wd2 = webdriverio.remote(options);
wd2.requestHandler.sessionID=wd.requestHandler.sessionID;
wd2.url('http://www.seamless.com');
share|improve this answer

I faced the same issue using TestNG. I had used @BeforeMethod and for each method new browser is opened.

When I changed it to @BeforeTest instead of @BeforeMethod, that worked for me.

share|improve this answer
    
If you pass in the driver instance via test method argument (from the DataProvider, then you want to use BeforeMethod, but if you have a shared driver in the class for multiple test methods (which i think is a bad idea) then you want to use BeforeTest, of course. – djangofan Feb 1 at 2:20

I had put my code to implement for new webdriver code as below ,refer this page: https://github.com/becausetesting/commons/blob/master/src/main/java/com/github/becausetesting/cucumber/selenium/RemoteWebDriverEx.java : just use this code to use existing started selenium session:

WebDriver driver=new RemoteWebDriverEx(true);

full code as below sample:

package com.github.becausetesting.cucumber.selenium;


@SuppressWarnings("deprecation")
public class RemoteWebDriverEx extends RemoteWebDriver {

    // TODO(dawagner): This static logger should be unified with the
    // per-instance localLogs
    /*
     * 
     * 2016/03/07 Alter: Add the use exising session for testing
     */
    private static final Logger logger = Logger.getLogger(RemoteWebDriverEx.class.getName());
    private Level level = Level.FINE;

    private ErrorHandler errorHandler = new ErrorHandler();
    private CommandExecutor executor;
    private Capabilities capabilities;
    private SessionId sessionId;
    private FileDetector fileDetector = new UselessFileDetector();
    private ExecuteMethod executeMethod;

    private JsonToWebElementConverter converter;

    private RemoteKeyboard keyboard;
    private RemoteMouse mouse;
    private Logs remoteLogs;
    private LocalLogs localLogs;

    private int w3cComplianceLevel = 0;

    private boolean useSession=false;

    public void useSeleniumSession(boolean useSession){
        this.useSession=useSession;
    }
    // For default testing to switch to firefox
    protected RemoteWebDriverEx() {
        this((URL) null, DesiredCapabilities.firefox());
    }


    protected RemoteWebDriverEx(boolean useSessionId) {
        this((URL) null, DesiredCapabilities.firefox(), useSessionId);
    }

    public RemoteWebDriverEx(CommandExecutor executor, Capabilities desiredCapabilities,
            Capabilities requiredCapabilities, boolean useSessionId) {
        this.executor = executor;


        //recover scenario script
        Thread.currentThread();
        Thread.setDefaultUncaughtExceptionHandler(new RecoveryScenario());

        init(desiredCapabilities, requiredCapabilities);

        if (executor instanceof NeedsLocalLogs) {
            ((NeedsLocalLogs) executor).setLocalLogs(localLogs);
        }
        if (useSessionId) {
            getExistingSessionId();
        }
        if (this.sessionId == null) {
            try {
                startClient();
            } catch (RuntimeException e) {
                try {
                    stopClient();
                } catch (Exception ignored) {
                    // Ignore the clean-up exception. We'll propagate the
                    // original failure.
                }

                throw e;
            }

            try {
                startSession(desiredCapabilities, requiredCapabilities);
            } catch (RuntimeException e) {
                try {
                    quit();
                } catch (Exception ignored) {
                    // Ignore the clean-up exception. We'll propagate the
                    // original
                    // failure.
                }

                throw e;
            }
        }

    }

    public RemoteWebDriverEx(CommandExecutor executor, Capabilities desiredCapabilities) {
        this(executor, desiredCapabilities, null, false);
    }

    public RemoteWebDriverEx(Capabilities desiredCapabilities) {
        this((URL) null, desiredCapabilities);
    }

    public RemoteWebDriverEx(Capabilities desiredCapabilities, boolean useSessionId) {
        this((URL) null, desiredCapabilities, useSessionId);
    }

    public RemoteWebDriverEx(URL remoteAddress, Capabilities desiredCapabilities, Capabilities requiredCapabilities) {
        this(new HttpCommandExecutor(remoteAddress), desiredCapabilities, requiredCapabilities, false);
    }

    public RemoteWebDriverEx(URL remoteAddress, Capabilities desiredCapabilities, Capabilities requiredCapabilities,
            boolean useSessionId) {
        this(new HttpCommandExecutor(remoteAddress), desiredCapabilities, requiredCapabilities, useSessionId);
    }

    public RemoteWebDriverEx(URL remoteAddress, Capabilities desiredCapabilities) {
        this(new HttpCommandExecutor(remoteAddress), desiredCapabilities, null, true);
    }

    public RemoteWebDriverEx(URL remoteAddress, Capabilities desiredCapabilities, boolean useSessionId) {
        this(new HttpCommandExecutor(remoteAddress), desiredCapabilities, null, useSessionId);
    }

    public int getW3CStandardComplianceLevel() {
        return w3cComplianceLevel;
    }

    private void init(Capabilities desiredCapabilities, Capabilities requiredCapabilities) {
        //logger.addHandler(LoggingHandler.getInstance());

        converter = new JsonToWebElementConverter(this);
        executeMethod = new RemoteExecuteMethod(this);
        keyboard = new RemoteKeyboard(executeMethod);
        mouse = new RemoteMouse(executeMethod);

        ImmutableSet.Builder<String> builder = new ImmutableSet.Builder<String>();

        boolean isProfilingEnabled = desiredCapabilities != null
                && desiredCapabilities.is(CapabilityType.ENABLE_PROFILING_CAPABILITY);
        if (requiredCapabilities != null
                && requiredCapabilities.getCapability(CapabilityType.ENABLE_PROFILING_CAPABILITY) != null) {
            isProfilingEnabled = requiredCapabilities.is(CapabilityType.ENABLE_PROFILING_CAPABILITY);
        }
        if (isProfilingEnabled) {
            builder.add(LogType.PROFILER);
        }

        LoggingPreferences mergedLoggingPrefs = new LoggingPreferences();
        if (desiredCapabilities != null) {
            mergedLoggingPrefs.addPreferences(
                    (LoggingPreferences) desiredCapabilities.getCapability(CapabilityType.LOGGING_PREFS));
        }
        if (requiredCapabilities != null) {
            mergedLoggingPrefs.addPreferences(
                    (LoggingPreferences) requiredCapabilities.getCapability(CapabilityType.LOGGING_PREFS));
        }
        if ((mergedLoggingPrefs.getEnabledLogTypes().contains(LogType.CLIENT)
                && mergedLoggingPrefs.getLevel(LogType.CLIENT) != Level.OFF)
                || !mergedLoggingPrefs.getEnabledLogTypes().contains(LogType.CLIENT)) {
            builder.add(LogType.CLIENT);
        }

        Set<String> logTypesToInclude = builder.build();

        LocalLogs performanceLogger = LocalLogs.getStoringLoggerInstance(logTypesToInclude);
        LocalLogs clientLogs = LocalLogs.getHandlerBasedLoggerInstance(LoggingHandler.getInstance(), logTypesToInclude);
        localLogs = LocalLogs.getCombinedLogsHolder(clientLogs, performanceLogger);
        remoteLogs = new RemoteLogs(executeMethod, localLogs);
    }

    /**
     * Set the file detector to be used when sending keyboard input. By default,
     * this is set to a file detector that does nothing.
     *
     * @param detector
     *            The detector to use. Must not be null.
     * @see FileDetector
     * @see LocalFileDetector
     * @see UselessFileDetector
     */
    public void setFileDetector(FileDetector detector) {
        if (detector == null) {
            throw new WebDriverException("You may not set a file detector that is null");
        }
        fileDetector = detector;
    }

    public SessionId getSessionId() {
        return sessionId;
    }

    public Capabilities getCapabilities() {
        return capabilities;
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    public void getExistingSessionId() {

        Response response = execute(DriverCommand.GET_ALL_SESSIONS);
        ArrayList sessionsList = (ArrayList) response.getValue();
        int size = sessionsList.size();
        if (size > 0) {
            // Here it will get the first sesion container ,if you have multiply
            // sesssion ,it always get the top sessions in the session
            // containers
            Map<String, Object> rawCapabilities = (Map<String, Object>) sessionsList.get(sessionsList.size() - 1);

            DesiredCapabilities returnedCapabilities = new DesiredCapabilities();
            for (Map.Entry<String, Object> entry : rawCapabilities.entrySet()) {
                // Handle the platform later
                if (CapabilityType.PLATFORM.equals(entry.getKey())) {
                    continue;
                }
                returnedCapabilities.setCapability(entry.getKey(), entry.getValue());
            }
            String platformString = (String) rawCapabilities.get(CapabilityType.PLATFORM);
            Platform platform;
            try {
                if (platformString == null || "".equals(platformString)) {
                    platform = Platform.ANY;
                } else {
                    platform = Platform.valueOf(platformString);
                }
            } catch (IllegalArgumentException e) {
                // The server probably responded with a name matching the
                // os.name
                // system property. Try to recover and parse this.
                platform = Platform.extractFromSysProperty(platformString);
            }
            returnedCapabilities.setPlatform(platform);

            capabilities = returnedCapabilities;
            String oldsessionid = (String) rawCapabilities.get("id");
            sessionId = new SessionId(oldsessionid);
            logger.info("Found Existing sessionId: " + oldsessionid
                    + " from session container,and emulate all the operations in this session.");
            if (response.getStatus() == null) {
                w3cComplianceLevel = 1;
            }
        }

    }

    protected void setSessionId(String opaqueKey) {
        sessionId = new SessionId(opaqueKey);
    }

    protected void startSession(Capabilities desiredCapabilities) {
        startSession(desiredCapabilities, null);
    }

    @SuppressWarnings({ "unchecked" })
    protected void startSession(Capabilities desiredCapabilities, Capabilities requiredCapabilities) {

        ImmutableMap.Builder<String, Capabilities> paramBuilder = new ImmutableMap.Builder<String, Capabilities>();
        paramBuilder.put("desiredCapabilities", desiredCapabilities);
        if (requiredCapabilities != null) {
            paramBuilder.put("requiredCapabilities", requiredCapabilities);
        }
        Map<String, ?> parameters = paramBuilder.build();

        Response response = execute(DriverCommand.NEW_SESSION, parameters);

        Map<String, Object> rawCapabilities = (Map<String, Object>) response.getValue();
        DesiredCapabilities returnedCapabilities = new DesiredCapabilities();
        for (Map.Entry<String, Object> entry : rawCapabilities.entrySet()) {
            // Handle the platform later
            if (CapabilityType.PLATFORM.equals(entry.getKey())) {
                continue;
            }
            returnedCapabilities.setCapability(entry.getKey(), entry.getValue());
        }
        String platformString = (String) rawCapabilities.get(CapabilityType.PLATFORM);
        Platform platform;
        try {
            if (platformString == null || "".equals(platformString)) {
                platform = Platform.ANY;
            } else {
                platform = Platform.valueOf(platformString);
            }
        } catch (IllegalArgumentException e) {
            // The server probably responded with a name matching the os.name
            // system property. Try to recover and parse this.
            platform = Platform.extractFromSysProperty(platformString);
        }
        returnedCapabilities.setPlatform(platform);

        capabilities = returnedCapabilities;
        sessionId = new SessionId(response.getSessionId());
        if (response.getStatus() == null) {
            w3cComplianceLevel = 1;
        }
    }

    public Object executeScript(String script, Object... args) {
        if (!capabilities.isJavascriptEnabled()) {
            throw new UnsupportedOperationException(
                    "You must be using an underlying instance of WebDriver that supports executing javascript");
        }

        // Escape the quote marks
        script = script.replaceAll("\"", "\\\"");

        Iterable<Object> convertedArgs = Iterables.transform(Lists.newArrayList(args), new WebElementToJsonConverter());

        Map<String, ?> params = ImmutableMap.of("script", script, "args", Lists.newArrayList(convertedArgs));

        if (getW3CStandardComplianceLevel() > 0) {
            return execute(DriverCommand.EXECUTE_SCRIPT_W3C, params).getValue();
        }
        return execute(DriverCommand.EXECUTE_SCRIPT, params).getValue();
    }

    public Object executeAsyncScript(String script, Object... args) {
        if (!isJavascriptEnabled()) {
            throw new UnsupportedOperationException(
                    "You must be using an underlying instance of " + "WebDriver that supports executing javascript");
        }

        // Escape the quote marks
        script = script.replaceAll("\"", "\\\"");

        Iterable<Object> convertedArgs = Iterables.transform(Lists.newArrayList(args), new WebElementToJsonConverter());

        Map<String, ?> params = ImmutableMap.of("script", script, "args", Lists.newArrayList(convertedArgs));

        if (getW3CStandardComplianceLevel() > 0) {
            return execute(DriverCommand.EXECUTE_ASYNC_SCRIPT_W3C, params).getValue();
        }
        return execute(DriverCommand.EXECUTE_ASYNC_SCRIPT, params).getValue();
    }

    private boolean isJavascriptEnabled() {
        return capabilities.isJavascriptEnabled();
    }

    public Options manage() {
        return new RemoteWebDriverOptions();
    }

    protected void setElementConverter(JsonToWebElementConverter converter) {
        this.converter = converter;
    }

    protected JsonToWebElementConverter getElementConverter() {
        return converter;
    }

    protected Response execute(String driverCommand, Map<String, ?> parameters) {
        Command command = new Command(sessionId, driverCommand, parameters);
        Response response;

        long start = System.currentTimeMillis();
        String currentName = Thread.currentThread().getName();
        Thread.currentThread()
                .setName(String.format("Forwarding %s on session %s to remote", driverCommand, sessionId));
        try {
            log(sessionId, command.getName(), command, When.BEFORE);
            response = executor.execute(command);
            log(sessionId, command.getName(), command, When.AFTER);

            if (response == null) {
                return null;
            }

            // Unwrap the response value by converting any JSON objects of the
            // form
            // {"ELEMENT": id} to RemoteWebElements.
            Object value = converter.apply(response.getValue());
            response.setValue(value);
        } catch (SessionNotFoundException e) {
            throw e;
        } catch (Exception e) {
            log(sessionId, command.getName(), command, When.EXCEPTION);
            String errorMessage = "Error communicating with the remote browser. " + "It may have died.";
            if (driverCommand.equals(DriverCommand.NEW_SESSION)) {
                errorMessage = "Could not start a new session. Possible causes are "
                        + "invalid address of the remote server or browser start-up failure.";
            }
            UnreachableBrowserException ube = new UnreachableBrowserException(errorMessage, e);
            if (getSessionId() != null) {
                ube.addInfo(WebDriverException.SESSION_ID, getSessionId().toString());
            }
            if (getCapabilities() != null) {
                ube.addInfo("Capabilities", getCapabilities().toString());
            }
            throw ube;
        } finally {
            Thread.currentThread().setName(currentName);
        }

        try {
            errorHandler.throwIfResponseFailed(response, System.currentTimeMillis() - start);
        } catch (WebDriverException ex) {
            if (parameters != null && parameters.containsKey("using") && parameters.containsKey("value")) {
                ex.addInfo("*** Element info",
                        String.format("{Using=%s, value=%s}", parameters.get("using"), parameters.get("value")));
            }
            ex.addInfo(WebDriverException.DRIVER_INFO, this.getClass().getName());
            if (getSessionId() != null) {
                ex.addInfo(WebDriverException.SESSION_ID, getSessionId().toString());
            }
            if (getCapabilities() != null) {
                ex.addInfo("Capabilities", getCapabilities().toString());
            }
            Throwables.propagate(ex);
        }
        return response;
    }

    protected Response execute(String command) {
        return execute(command, ImmutableMap.<String, Object> of());
    }

    protected ExecuteMethod getExecuteMethod() {
        return executeMethod;
    }

    public Keyboard getKeyboard() {
        return keyboard;
    }

    public Mouse getMouse() {
        return mouse;
    }

    /**
     * Override this to be notified at key points in the execution of a command.
     *
     * @param sessionId
     *            the session id.
     * @param commandName
     *            the command that is being executed.
     * @param toLog
     *            any data that might be interesting.
     * @param when
     *            verb tense of "Execute" to prefix message
     */
    protected void log(SessionId sessionId, String commandName, Object toLog, When when) {
        String text = "" + toLog;
        if (commandName.equals(DriverCommand.EXECUTE_SCRIPT)
                || commandName.equals(DriverCommand.EXECUTE_ASYNC_SCRIPT)) {
            if (text.length() > 100 && Boolean.getBoolean("webdriver.remote.shorten_log_messages")) {
                text = text.substring(0, 100) + "...";
            }
        }
        switch (when) {
        case BEFORE:
            logger.info( "Executing: " + commandName + " " + text);
            break;
        case AFTER:
            logger.info("Executed: " + text);
            break;
        case EXCEPTION:
            logger.info("Exception: " + text);
            break;
        default:
            logger.info( text);
            break;
        }
    }

    public FileDetector getFileDetector() {
        return fileDetector;
    }

    protected class RemoteWebDriverOptions implements Options {

        @Beta
        public Logs logs() {
            return remoteLogs;
        }

        public void addCookie(Cookie cookie) {
            cookie.validate();
            execute(DriverCommand.ADD_COOKIE, ImmutableMap.of("cookie", cookie));
        }

        public void deleteCookieNamed(String name) {
            execute(DriverCommand.DELETE_COOKIE, ImmutableMap.of("name", name));
        }

        public void deleteCookie(Cookie cookie) {
            deleteCookieNamed(cookie.getName());
        }

        public void deleteAllCookies() {
            Object response = execute(DriverCommand.DELETE_ALL_COOKIES);
            System.out.println(response);
        }

        @SuppressWarnings({ "unchecked" })
        public Set<Cookie> getCookies() {
            Object returned = execute(DriverCommand.GET_ALL_COOKIES).getValue();

            Set<Cookie> toReturn = new HashSet<>();

            List<Map<String, Object>> cookies = new JsonToBeanConverter().convert(List.class, returned);
            if (cookies == null) {
                return toReturn;
            }

            for (Map<String, Object> rawCookie : cookies) {
                String name = (String) rawCookie.get("name");
                String value = (String) rawCookie.get("value");
                String path = (String) rawCookie.get("path");
                String domain = (String) rawCookie.get("domain");
                boolean secure = rawCookie.containsKey("secure") && (Boolean) rawCookie.get("secure");

                Number expiryNum = (Number) rawCookie.get("expiry");
                Date expiry = expiryNum == null ? null : new Date(TimeUnit.SECONDS.toMillis(expiryNum.longValue()));

                toReturn.add(new Cookie.Builder(name, value).path(path).domain(domain).isSecure(secure)
                        .expiresOn(expiry).build());
            }

            return toReturn;
        }

        public Cookie getCookieNamed(String name) {
            Set<Cookie> allCookies = getCookies();
            for (Cookie cookie : allCookies) {
                if (cookie.getName().equals(name)) {
                    return cookie;
                }
            }
            return null;
        }

        public Timeouts timeouts() {
            return new RemoteTimeouts();
        }

        public ImeHandler ime() {
            return new RemoteInputMethodManager();
        }

        @Beta
        public Window window() {
            return new RemoteWindow();
        }

        protected class RemoteInputMethodManager implements WebDriver.ImeHandler {

            @SuppressWarnings("unchecked")
            public List<String> getAvailableEngines() {
                Response response = execute(DriverCommand.IME_GET_AVAILABLE_ENGINES);
                return (List<String>) response.getValue();
            }

            public String getActiveEngine() {
                Response response = execute(DriverCommand.IME_GET_ACTIVE_ENGINE);
                return (String) response.getValue();
            }

            public boolean isActivated() {
                Response response = execute(DriverCommand.IME_IS_ACTIVATED);
                return (Boolean) response.getValue();
            }

            public void deactivate() {
                execute(DriverCommand.IME_DEACTIVATE);
            }

            public void activateEngine(String engine) {
                execute(DriverCommand.IME_ACTIVATE_ENGINE, ImmutableMap.of("engine", engine));
            }
        } // RemoteInputMethodManager class

        protected class RemoteTimeouts implements Timeouts {

            public Timeouts implicitlyWait(long time, TimeUnit unit) {
                execute(DriverCommand.SET_TIMEOUT,
                        ImmutableMap.of("type", "implicit", "ms", TimeUnit.MILLISECONDS.convert(time, unit)));
                return this;
            }

            public Timeouts setScriptTimeout(long time, TimeUnit unit) {
                execute(DriverCommand.SET_TIMEOUT,
                        ImmutableMap.of("type", "script", "ms", TimeUnit.MILLISECONDS.convert(time, unit)));
                return this;
            }

            public Timeouts pageLoadTimeout(long time, TimeUnit unit) {
                execute(DriverCommand.SET_TIMEOUT,
                        ImmutableMap.of("type", "page load", "ms", TimeUnit.MILLISECONDS.convert(time, unit)));
                return this;
            }
        } // timeouts class.

        @Beta
        protected class RemoteWindow implements Window {

            public void setSize(Dimension targetSize) {
                if (getW3CStandardComplianceLevel() == 0) {
                    execute(DriverCommand.SET_WINDOW_SIZE, ImmutableMap.of("windowHandle", "current", "width",
                            targetSize.width, "height", targetSize.height));
                } else {
                    execute(DriverCommand.SET_CURRENT_WINDOW_SIZE,
                            ImmutableMap.of("width", targetSize.width, "height", targetSize.height));
                }
            }

            public void setPosition(Point targetPosition) {
                if (getW3CStandardComplianceLevel() == 0) {
                    execute(DriverCommand.SET_WINDOW_POSITION,
                            ImmutableMap.of("windowHandle", "current", "x", targetPosition.x, "y", targetPosition.y));
                } else {
                    executeScript("window.screenX = arguments[0]; window.screenY = arguments[1]", targetPosition.x,
                            targetPosition.y);
                }
            }

            @SuppressWarnings({ "unchecked" })
            public Dimension getSize() {
                Response response = getW3CStandardComplianceLevel() == 0
                        ? execute(DriverCommand.GET_WINDOW_SIZE, ImmutableMap.of("windowHandle", "current"))
                        : execute(DriverCommand.GET_CURRENT_WINDOW_SIZE);

                Map<String, Object> rawSize = (Map<String, Object>) response.getValue();

                int width = ((Number) rawSize.get("width")).intValue();
                int height = ((Number) rawSize.get("height")).intValue();

                return new Dimension(width, height);
            }

            Map<String, Object> rawPoint;

            @SuppressWarnings("unchecked")
            public Point getPosition() {
                if (getW3CStandardComplianceLevel() == 0) {
                    Response response = execute(DriverCommand.GET_WINDOW_POSITION,
                            ImmutableMap.of("windowHandle", "current"));
                    rawPoint = (Map<String, Object>) response.getValue();
                } else {
                    rawPoint = (Map<String, Object>) executeScript("return {x: window.screenX, y: window.screenY}");
                }

                int x = ((Number) rawPoint.get("x")).intValue();
                int y = ((Number) rawPoint.get("y")).intValue();

                return new Point(x, y);
            }

            public void maximize() {
                if (getW3CStandardComplianceLevel() == 0) {
                    execute(DriverCommand.MAXIMIZE_WINDOW, ImmutableMap.of("windowHandle", "current"));
                } else {
                    execute(DriverCommand.MAXIMIZE_CURRENT_WINDOW);
                }
            }

            public void fullscreen() {
                execute(DriverCommand.FULLSCREEN_CURRENT_WINDOW);
            }
        }
    }


    protected class RemoteTargetLocator implements TargetLocator {

        public WebDriver frame(int frameIndex) {
            execute(DriverCommand.SWITCH_TO_FRAME, ImmutableMap.of("id", frameIndex));
            return RemoteWebDriverEx.this;
        }

        public WebDriver frame(String frameName) {
            String name = frameName.replaceAll("(['\"\\\\#.:;,!?+<>=~*^$|%&@`{}\\-/\\[\\]\\(\\)])", "\\\\$1");
            List<WebElement> frameElements = RemoteWebDriverEx.this
                    .findElements(By.cssSelector("frame[name='" + name + "'],iframe[name='" + name + "']"));
            if (frameElements.size() == 0) {
                frameElements = RemoteWebDriverEx.this.findElements(By.cssSelector("frame#" + name + ",iframe#" + name));
            }
            if (frameElements.size() == 0) {
                throw new NoSuchFrameException("No frame element found by name or id " + frameName);
            }
            return frame(frameElements.get(0));
        }

        public WebDriver frame(WebElement frameElement) {
            Object elementAsJson = new WebElementToJsonConverter().apply(frameElement);
            execute(DriverCommand.SWITCH_TO_FRAME, ImmutableMap.of("id", elementAsJson));
            return RemoteWebDriverEx.this;
        }

        public WebDriver parentFrame() {
            execute(DriverCommand.SWITCH_TO_PARENT_FRAME);
            return RemoteWebDriverEx.this;
        }

        public WebDriver window(String windowHandleOrName) {
            if (getW3CStandardComplianceLevel() == 0) {
                execute(DriverCommand.SWITCH_TO_WINDOW, ImmutableMap.of("name", windowHandleOrName));
                return RemoteWebDriverEx.this;
            } else {
                try {
                    execute(DriverCommand.SWITCH_TO_WINDOW, ImmutableMap.of("handle", windowHandleOrName));
                    return RemoteWebDriverEx.this;
                } catch (NoSuchWindowException nsw) {
                    // simulate search by name
                    String original = getWindowHandle();
                    for (String handle : getWindowHandles()) {
                        switchTo().window(handle);
                        if (windowHandleOrName.equals(executeScript("return window.name"))) {
                            return RemoteWebDriverEx.this; // found by name
                        }
                    }
                    switchTo().window(original);
                    throw nsw;
                }
            }
        }

        public WebDriver defaultContent() {
            Map<String, Object> frameId = Maps.newHashMap();
            frameId.put("id", null);
            execute(DriverCommand.SWITCH_TO_FRAME, frameId);
            return RemoteWebDriverEx.this;
        }

        public WebElement activeElement() {
            Response response = execute(DriverCommand.GET_ACTIVE_ELEMENT);
            return (WebElement) response.getValue();
        }

        public Alert alert() {
            execute(DriverCommand.GET_ALERT_TEXT);
            return new RemoteAlert();
        }
    }

    private class RemoteAlert implements Alert {

        public RemoteAlert() {
        }

        public void dismiss() {
            if (getW3CStandardComplianceLevel() > 0) {
                execute(DriverCommand.DISMISS_ALERT_W3C);
            } else {
                execute(DriverCommand.DISMISS_ALERT);
            }
        }


}
share|improve this answer
    
Hi Alter! I don't understand what that constructor does. I looked into the class you linked and found the variable it sets, but that variable doesn't seem to ever get used! How does this work? – corsiKa Jun 22 at 17:43
    
@corsiKa which variable you mentioned here, here i overwrite the RemoteWebDriver class and passed a separate new parameter to indecate whether you want to use the existing selenium session or not. if set to true ,it will found any existing session in your remote web driver server. please let me know what's your question? thanks . – Alter.hu Jun 23 at 4:29
    
Your snippet of WebDriver driver=new RemoteWebDriverEx(true); - inside the GitHub link, that true variable in the constructor gets set inside the class to a private variable. But that private variable is not used anywhere in the class. So... what exactly does it do? – corsiKa Jun 23 at 15:04
    
yes @corsiKa,Sorry for my later reply ,i had update the code to new implement,thanks for your reviewing .the below is the updated code :github.com/becausetesting/commons/blob/master/src/main/java/com/… – Alter.hu Jul 1 at 4:50

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.