Skip to content

Instantly share code, notes, and snippets.

@tristanstraub
Last active February 16, 2017 20:34
Show Gist options
  • Save tristanstraub/d1c36ddaf9dcced570a6 to your computer and use it in GitHub Desktop.
Save tristanstraub/d1c36ddaf9dcced570a6 to your computer and use it in GitHub Desktop.
webdriverReattach = require './webdriverReattach'
webdriverReattach.captureBrowser()
exports.config =
seleniumAddress: 'http://localhost:4444/wd/hub'
# -- protractor overrides to capture existing browser session
base = require 'selenium-webdriver/_base'
webdriver = base.require 'webdriver.WebDriver'
assert = require 'assert'
Q = require 'q'
fs = require 'fs'
path = require 'path'
BROWSER_SESSION_FILE_PATH = path.join(__dirname, './browser-session.json')
sessionFile =
saveId: (sessionId) ->
content = {sessionId}
fs.writeFileSync BROWSER_SESSION_FILE_PATH, JSON.stringify content, null, 2
loadId: ->
try
return (JSON.parse fs.readFileSync BROWSER_SESSION_FILE_PATH).sessionId
catch e
return null
hookDriverSession = (driver) ->
# Save the sessionId when it is available
driver.getSession().then (createdSession) ->
sessionFile.saveId createdSession.getId()
driver.quit = ->
d = Q.defer()
d.resolve()
return d.promise
return driver
createSession = webdriver.createSession
getDriverHooks = (sessionId, {executor, capabilities, flow}) ->
return {
getNewSessionDriver: ->
return createSession(executor, capabilities, flow)
getAttachedSessionDriver: ->
d = Q.defer()
session = d.promise
createNewSession = ->
createSession(executor, capabilities, flow).getSession().then (createdSession) -> d.resolve createdSession
testAttachedSession = (attachedSession) ->
new webdriver(attachedSession, executor, flow).executeScript('console.log("attached")')
.then (-> d.resolve attachedSession), createNewSession
webdriver.attachToSession(executor, sessionId, flow).getSession()
.then testAttachedSession, createNewSession
return hookDriverSession(new webdriver(session, executor, flow))
}
captured = false
exports.captureBrowser = ->
assert !captured, 'Browser has already been captured'
captured = true
webdriver.createSession = (executor, capabilities, flow) ->
sessionId = sessionFile.loadId()
{getNewSessionDriver, getAttachedSessionDriver} = getDriverHooks sessionId, {executor, capabilities, flow}
driver = if !sessionId then getNewSessionDriver() else getAttachedSessionDriver()
return hookDriverSession driver
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment