How to reuse session id to return to last url and browser

Posting my solution for anyone that needs it because I had a hard time finding the answer for this. This allows you to close your browser session and reopen on the next test. I’m not asking how, I’m telling what worked for me. Maybe it will help someone. I was using windows, hence the backslashes.

###Put this in your resource file

*** Settings ***
Library           OperatingSystem
Library           Process
Library           String
Library           RequestsLibrary
Library           Collections
Library           RPA.Browser.Selenium
Resource          resource.resource

*** Keywords ***
reUsePage1
    Comment    This is how your tests can reuse browser sessions. Put keyword reUsePage1 at end of each test. Put reUsePage2 at start of each test.
    ${currentUrl}    Get Location
    log to console    ${currentUrl}
    Set Global Variable    ${url}    ${currentUrl}
    Create File    ${TEMPDIR}\\currentUrl.txt    ${currentUrl}
    ${session_id}    Get Session Id
    ${attach_to_session}    RPA.Browser.Selenium.Get WebElements    ${session_id}
    ${session}    Convert To String    ${attach_to_session}
    Log    ${session}    console=Yes
    Create File    ${TEMPDIR}\\currentId.txt    ${session}
    Close Browser

reUsePage2
    Log    Reusing Driver    console=Yes
    ${contents}=    Get File    ${CURDIR}\\currentId.txt
    ${session}=    Get Line    ${contents}    0
    ${session}=    Convert To String    ${session}
    Log    ${session}    console=yes
    Create Webdriver    Chrome ${session}
    Maximize Browser Window
    ${contents}=    Get File    ${CURDIR}\\currentUrl.txt
    ${session_url}=    Get Line    ${contents}    0
    Sleep    10s
    Go To    ${session_url}
    Maximize Browser Window

###Example of how to use it in your test

*** Test Cases ***
Test0_chrome
    [Tags]    chrome
    ${chrome_options}    Evaluate    sys.modules['selenium.webdriver'].ChromeOptions()    sys, selenium.webdriver
    Call Method    ${chrome_options}    add_argument    --test-type
    Call Method    ${chrome_options}    add_argument    --no-sandbox
    Call Method    ${chrome_options}    add_argument    --disable-dev-shm-usage
    Call Method    ${chrome_options}    add_argument    --start-maximized
    Create Webdriver    Chrome    chrome_options=${chrome_options}
    Go To    https://forum.robotframework.org/
    reUsePage1

Test1_Search
    reUsePage2
    Wait Until Element Is Visible    id=site-logo    30s
    Click Element    id=site-logo
    reUsePage1
2 Likes