How to use driver.windowHandles method in Appium

Best JavaScript code snippet using appium

command.js

Source:command.js Github

copy

Full Screen

1// Licensed to the Software Freedom Conservancy (SFC) under one2// or more contributor license agreements.  See the NOTICE file3// distributed with this work for additional information4// regarding copyright ownership.  The SFC licenses this file5// to you under the Apache License, Version 2.0 (the6// "License"); you may not use this file except in compliance7// with the License.  You may obtain a copy of the License at8//9//   http://www.apache.org/licenses/LICENSE-2.010//11// Unless required by applicable law or agreed to in writing,12// software distributed under the License is distributed on an13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY14// KIND, either express or implied.  See the License for the15// specific language governing permissions and limitations16// under the License.17import { codeExport as exporter } from '@seleniumhq/side-utils'18import location from './location'19import selection from './selection'20export const emitters = {21  addSelection: emitSelect,22  answerOnNextPrompt: skip,23  assert: emitAssert,24  assertAlert: emitAssertAlert,25  assertChecked: emitVerifyChecked,26  assertConfirmation: emitAssertAlert,27  assertEditable: emitVerifyEditable,28  assertElementPresent: emitVerifyElementPresent,29  assertElementNotPresent: emitVerifyElementNotPresent,30  assertNotChecked: emitVerifyNotChecked,31  assertNotEditable: emitVerifyNotEditable,32  assertNotSelectedValue: emitVerifyNotSelectedValue,33  assertNotText: emitVerifyNotText,34  assertPrompt: emitAssertAlert,35  assertSelectedLabel: emitVerifySelectedLabel,36  assertSelectedValue: emitVerifySelectedValue,37  assertValue: emitVerifyValue,38  assertText: emitVerifyText,39  assertTitle: emitVerifyTitle,40  check: emitCheck,41  chooseCancelOnNextConfirmation: skip,42  chooseCancelOnNextPrompt: skip,43  chooseOkOnNextConfirmation: skip,44  click: emitClick,45  clickAt: emitClick,46  close: emitClose,47  debugger: skip,48  do: emitControlFlowDo,49  doubleClick: emitDoubleClick,50  doubleClickAt: emitDoubleClick,51  dragAndDropToObject: emitDragAndDrop,52  echo: emitEcho,53  editContent: emitEditContent,54  else: emitControlFlowElse,55  elseIf: emitControlFlowElseIf,56  end: emitControlFlowEnd,57  executeScript: emitExecuteScript,58  executeAsyncScript: emitExecuteAsyncScript,59  forEach: emitControlFlowForEach,60  if: emitControlFlowIf,61  mouseDown: emitMouseDown,62  mouseDownAt: emitMouseDown,63  mouseMove: emitMouseMove,64  mouseMoveAt: emitMouseMove,65  mouseOver: emitMouseMove,66  mouseOut: emitMouseOut,67  mouseUp: emitMouseUp,68  mouseUpAt: emitMouseUp,69  open: emitOpen,70  pause: emitPause,71  removeSelection: emitSelect,72  repeatIf: emitControlFlowRepeatIf,73  run: emitRun,74  runScript: emitRunScript,75  select: emitSelect,76  selectFrame: emitSelectFrame,77  selectWindow: emitSelectWindow,78  sendKeys: emitSendKeys,79  setSpeed: emitSetSpeed,80  setWindowSize: emitSetWindowSize,81  store: emitStore,82  storeAttribute: emitStoreAttribute,83  storeJson: emitStoreJson,84  storeText: emitStoreText,85  storeTitle: emitStoreTitle,86  storeValue: emitStoreValue,87  storeWindowHandle: emitStoreWindowHandle,88  storeXpathCount: emitStoreXpathCount,89  submit: emitSubmit,90  times: emitControlFlowTimes,91  type: emitType,92  uncheck: emitUncheck,93  verify: emitAssert,94  verifyChecked: emitVerifyChecked,95  verifyEditable: emitVerifyEditable,96  verifyElementPresent: emitVerifyElementPresent,97  verifyElementNotPresent: emitVerifyElementNotPresent,98  verifyNotChecked: emitVerifyNotChecked,99  verifyNotEditable: emitVerifyNotEditable,100  verifyNotSelectedValue: emitVerifyNotSelectedValue,101  verifyNotText: emitVerifyNotText,102  verifySelectedLabel: emitVerifySelectedLabel,103  verifySelectedValue: emitVerifySelectedValue,104  verifyText: emitVerifyText,105  verifyTitle: emitVerifyTitle,106  verifyValue: emitVerifyValue,107  waitForElementEditable: emitWaitForElementEditable,108  waitForElementPresent: emitWaitForElementPresent,109  waitForElementVisible: emitWaitForElementVisible,110  waitForElementNotEditable: emitWaitForElementNotEditable,111  waitForElementNotPresent: emitWaitForElementNotPresent,112  waitForElementNotVisible: emitWaitForElementNotVisible,113  webDriverAnswerOnVisiblePrompt: emitAnswerOnNextPrompt,114  webDriverChooseCancelOnVisibleConfirmation: emitChooseCancelOnNextConfirmation,115  webDriverChooseCancelOnVisiblePrompt: emitChooseCancelOnNextConfirmation,116  webDriverChooseOkOnVisibleConfirmation: emitChooseOkOnNextConfirmation,117  while: emitControlFlowWhile,118}119exporter.register.preprocessors(emitters)120function register(command, emitter) {121  exporter.register.emitter({ command, emitter, emitters })122}123function emit(command) {124  return exporter.emit.command(command, emitters[command.command], {125    variableLookup,126    emitNewWindowHandling,127  })128}129function canEmit(commandName) {130  return !!emitters[commandName]131}132function variableLookup(varName) {133  return `vars["${varName}"].ToString()`134}135function variableSetter(varName, value) {136  return varName ? `vars["${varName}"] = ${value};` : ''137}138function emitWaitForWindow() {139  const generateMethodDeclaration = name => {140    return `public string ${name}(int timeout) {`141  }142  const commands = [143    { level: 0, statement: 'try {' },144    { level: 1, statement: 'Thread.Sleep(timeout);' },145    { level: 0, statement: '} catch(Exception e) {' },146    { level: 1, statement: 'Console.WriteLine("{0} Exception caught.", e);' },147    { level: 0, statement: '}' },148    {149      level: 0,150      statement:151        'var whNow = ((IReadOnlyCollection<object>)driver.WindowHandles).ToList();',152    },153    {154      level: 0,155      statement:156        'var whThen = ((IReadOnlyCollection<object>)vars["WindowHandles"]).ToList();',157    },158    { level: 0, statement: 'if (whNow.Count > whThen.Count) {' },159    { level: 1, statement: 'return whNow.Except(whThen).First().ToString();' },160    { level: 0, statement: '} else {' },161    { level: 1, statement: 'return whNow.First().ToString();' },162    { level: 0, statement: '}' },163  ]164  return Promise.resolve({165    name: 'waitForWindow',166    commands,167    generateMethodDeclaration,168  })169}170async function emitNewWindowHandling(command, emittedCommand) {171  return Promise.resolve(172    `vars["WindowHandles"] = driver.WindowHandles;\n${await emittedCommand}\nvars["${173      command.windowHandleName174    }"] = waitForWindow(${command.windowTimeout});`175  )176}177function emitAssert(varName, value) {178  const _value =179    value === 'true' || value === 'false'180      ? exporter.parsers.capitalize(value)181      : value182  return Promise.resolve(183    `Assert.That(vars["${varName}"].ToString(), Is.EqualTo("${_value}"));`184  )185}186function emitAssertAlert(alertText) {187  return Promise.resolve(188    `Assert.That(driver.SwitchTo().Alert().Text, Is.EqualTo("${alertText}"));`189  )190}191function emitAnswerOnNextPrompt(textToSend) {192  const commands = [193    { level: 0, statement: '{' },194    { level: 1, statement: 'var Alert = driver.SwitchTo().Alert();' },195    { level: 1, statement: `Alert.SendKeys("${textToSend}")` },196    { level: 1, statement: 'Alert.Accept();' },197    { level: 0, statement: '}' },198  ]199  return Promise.resolve({ commands })200}201async function emitCheck(locator) {202  const commands = [203    { level: 0, statement: '{' },204    {205      level: 1,206      statement: `var element = driver.FindElement(${await location.emit(207        locator208      )});`,209    },210    { level: 1, statement: 'if (!element.Selected) {' },211    { level: 2, statement: 'element.Click();' },212    { level: 1, statement: '}' },213    { level: 0, statement: '}' },214  ]215  return Promise.resolve({ commands })216}217function emitChooseCancelOnNextConfirmation() {218  return Promise.resolve(`driver.SwitchTo().Alert().Dismiss();`)219}220function emitChooseOkOnNextConfirmation() {221  return Promise.resolve(`driver.SwitchTo().Alert().Accept();`)222}223async function emitClick(target) {224  return Promise.resolve(225    `driver.FindElement(${await location.emit(target)}).Click();`226  )227}228async function emitClose() {229  return Promise.resolve(`driver.Close();`)230}231function generateExpressionScript(script) {232  const scriptString = script.script.replace(/"/g, "'")233  return `(Boolean) js.ExecuteScript("return (${scriptString})"${generateScriptArguments(234    script235  )})`236}237function emitControlFlowDo() {238  return Promise.resolve({239    commands: [{ level: 0, statement: 'do {' }],240    endingLevelAdjustment: 1,241  })242}243function emitControlFlowElse() {244  return Promise.resolve({245    commands: [{ level: 0, statement: '} else {' }],246    startingLevelAdjustment: -1,247    endingLevelAdjustment: +1,248  })249}250function emitControlFlowElseIf(script) {251  return Promise.resolve({252    commands: [253      {254        level: 0,255        statement: `} else if (${generateExpressionScript(script)}) {`,256      },257    ],258    startingLevelAdjustment: -1,259    endingLevelAdjustment: +1,260  })261}262function emitControlFlowEnd() {263  return Promise.resolve({264    commands: [{ level: 0, statement: `}` }],265    startingLevelAdjustment: -1,266  })267}268function emitControlFlowIf(script) {269  return Promise.resolve({270    commands: [271      { level: 0, statement: `if (${generateExpressionScript(script)}) {` },272    ],273    endingLevelAdjustment: 1,274  })275}276function emitControlFlowForEach(collectionVarName, iteratorVarName) {277  return Promise.resolve({278    commands: [279      {280        level: 0,281        statement: `var ${collectionVarName}Enum = ((IReadOnlyCollection<object>)vars["${collectionVarName}"]).ToList().GetEnumerator();`,282      },283      {284        level: 0,285        statement: `while (${collectionVarName}Enum.MoveNext())`,286      },287      {288        level: 0,289        statement: `{`,290      },291      {292        level: 1,293        statement: `vars["${iteratorVarName}"] = ${collectionVarName}Enum.Current;`,294      },295    ],296  })297}298function emitControlFlowRepeatIf(script) {299  return Promise.resolve({300    commands: [301      { level: 0, statement: `} while (${generateExpressionScript(script)});` },302    ],303    startingLevelAdjustment: -1,304  })305}306function emitControlFlowTimes(target) {307  const commands = [308    { level: 0, statement: `var times = ${target};` },309    { level: 0, statement: 'for(int i = 0; i < times; i++) {' },310  ]311  return Promise.resolve({ commands, endingLevelAdjustment: 1 })312}313function emitControlFlowWhile(script) {314  return Promise.resolve({315    commands: [316      { level: 0, statement: `while (${generateExpressionScript(script)}) {` },317    ],318    endingLevelAdjustment: 1,319  })320}321async function emitDoubleClick(target) {322  const commands = [323    { level: 0, statement: '{' },324    {325      level: 1,326      statement: `var element = driver.FindElement(${await location.emit(327        target328      )});`,329    },330    { level: 1, statement: 'Actions builder = new Actions(driver);' },331    { level: 1, statement: 'builder.DoubleClick(element).Perform();' },332    { level: 0, statement: '}' },333  ]334  return Promise.resolve({ commands })335}336async function emitDragAndDrop(dragged, dropped) {337  const commands = [338    { level: 0, statement: '{' },339    {340      level: 1,341      statement: `var dragged = driver.FindElement(${await location.emit(342        dragged343      )});`,344    },345    {346      level: 1,347      statement: `var dropped = driver.FindElement(${await location.emit(348        dropped349      )});`,350    },351    { level: 1, statement: 'Actions builder = new Actions(driver);' },352    { level: 1, statement: 'builder.DragAndDrop(dragged, dropped).Perform();' },353    { level: 0, statement: '}' },354  ]355  return Promise.resolve({ commands })356}357async function emitEcho(message) {358  const _message = message.startsWith('vars[') ? message : `"${message}"`359  return Promise.resolve(`Console.WriteLine(${_message});`)360}361async function emitEditContent(locator, content) {362  const commands = [363    { level: 0, statement: '{' },364    {365      level: 1,366      statement: `var element = driver.FindElement(${await location.emit(367        locator368      )});`,369    },370    {371      level: 1,372      statement: `js.ExecuteScript("if(arguments[0].contentEditable === 'true') {arguments[0].innerText = '${content}'}", element);`,373    },374    { level: 0, statement: '}' },375  ]376  return Promise.resolve({ commands })377}378async function emitExecuteScript(script, varName) {379  const result = `js.ExecuteScript("${script.script}"${generateScriptArguments(380    script381  )})`382  return Promise.resolve(variableSetter(varName, result))383}384async function emitExecuteAsyncScript(script, varName) {385  const result = `js.executeAsyncScript("var callback = arguments[arguments.length - 1];${386    script.script387  }.then(callback).catch(callback);${generateScriptArguments(script)}")`388  return Promise.resolve(variableSetter(varName, result))389}390function generateScriptArguments(script) {391  return `${script.argv.length ? ', ' : ''}${script.argv392    .map(varName => `vars["${varName}"]`)393    .join(',')}`394}395async function emitMouseDown(locator) {396  const commands = [397    { level: 0, statement: '{' },398    {399      level: 1,400      statement: `var element = driver.FindElement(${await location.emit(401        locator402      )});`,403    },404    { level: 1, statement: 'Actions builder = new Actions(driver);' },405    {406      level: 1,407      statement: 'builder.MoveToElement(element).ClickAndHold().Perform();',408    },409    { level: 0, statement: '}' },410  ]411  return Promise.resolve({ commands })412}413async function emitMouseMove(locator) {414  const commands = [415    { level: 0, statement: '{' },416    {417      level: 1,418      statement: `var element = driver.FindElement(${await location.emit(419        locator420      )});`,421    },422    { level: 1, statement: 'Actions builder = new Actions(driver);' },423    { level: 1, statement: 'builder.MoveToElement(element).Perform();' },424    { level: 0, statement: '}' },425  ]426  return Promise.resolve({ commands })427}428async function emitMouseOut() {429  const commands = [430    { level: 0, statement: '{' },431    {432      level: 1,433      statement: `var element = driver.FindElement(By.tagName("body"));`,434    },435    { level: 1, statement: 'Actions builder = new Actions(driver);' },436    { level: 1, statement: 'builder.MoveToElement(element, 0, 0).Perform();' },437    { level: 0, statement: '}' },438  ]439  return Promise.resolve({ commands })440}441async function emitMouseUp(locator) {442  const commands = [443    { level: 0, statement: '{' },444    {445      level: 1,446      statement: `var element = driver.FindElement(${await location.emit(447        locator448      )});`,449    },450    { level: 1, statement: 'Actions builder = new Actions(driver);' },451    {452      level: 1,453      statement: 'builder.MoveToElement(element).Release().Perform();',454    },455    { level: 0, statement: '}' },456  ]457  return Promise.resolve({ commands })458}459function emitOpen(target) {460  const url = /^(file|http|https):\/\//.test(target)461    ? `"${target}"`462    : `"${global.baseUrl}${target}"`463  return Promise.resolve(`driver.Navigate().GoToUrl(${url});`)464}465async function emitPause(time) {466  const commands = [467    { level: 0, statement: 'try {' },468    { level: 1, statement: `Thread.Sleep(${time});` },469    { level: 0, statement: '} catch {' },470    { level: 1, statement: 'Console.WriteLine("{0} Exception caught.", e);' },471    { level: 0, statement: '}' },472  ]473  return Promise.resolve({ commands })474}475async function emitRun(testName) {476  return Promise.resolve(`${exporter.parsers.sanitizeName(testName)}();`)477}478async function emitRunScript(script) {479  return Promise.resolve(480    `js.ExecuteScript("${script.script}${generateScriptArguments(script)}");`481  )482}483async function emitSetWindowSize(size) {484  const [width, height] = size.split('x')485  return Promise.resolve(486    `driver.Manage().Window.Size = new System.Drawing.Size(${width}, ${height});`487  )488}489async function emitSelect(selectElement, option) {490  const commands = [491    { level: 0, statement: '{' },492    {493      level: 1,494      statement: `var dropdown = driver.FindElement(${await location.emit(495        selectElement496      )});`,497    },498    {499      level: 1,500      statement: `dropdown.FindElement(${await selection.emit(501        option502      )}).Click();`,503    },504    { level: 0, statement: '}' },505  ]506  return Promise.resolve({ commands })507}508async function emitSelectFrame(frameLocation) {509  if (frameLocation === 'relative=top' || frameLocation === 'relative=parent') {510    return Promise.resolve('driver.SwitchTo().DefaultContent();')511  } else if (/^index=/.test(frameLocation)) {512    return Promise.resolve(513      `driver.SwitchTo().Frame(${Math.floor(514        frameLocation.split('index=')[1]515      )});`516    )517  } else {518    return Promise.resolve({519      commands: [520        { level: 0, statement: '{' },521        {522          level: 1,523          statement: `var element = driver.FindElement(${await location.emit(524            frameLocation525          )});`,526        },527        { level: 1, statement: 'driver.SwitchTo().Frame(element);' },528        { level: 0, statement: '}' },529      ],530    })531  }532}533async function emitSelectWindow(windowLocation) {534  if (/^handle=/.test(windowLocation)) {535    return Promise.resolve(536      `driver.SwitchTo().Window(${windowLocation.split('handle=')[1]});`537    )538  } else if (/^name=/.test(windowLocation)) {539    return Promise.resolve(540      `driver.SwitchTo().Window("${windowLocation.split('name=')[1]}");`541    )542  } else if (/^win_ser_/.test(windowLocation)) {543    if (windowLocation === 'win_ser_local') {544      return Promise.resolve({545        commands: [546          { level: 0, statement: '{' },547          {548            level: 1,549            statement:550              'ArrayList<string> handles = new ArrayList<string>(driver.WindowHandles());',551          },552          { level: 1, statement: 'driver.SwitchTo().Window(handles[0]);' },553          { level: 0, statement: '}' },554        ],555      })556    } else {557      const index = parseInt(windowLocation.substr('win_ser_'.length))558      return Promise.resolve({559        commands: [560          { level: 0, statement: '{' },561          {562            level: 1,563            statement:564              'ArrayList<string> handles = new ArrayList<string>(driver.WindowHandles);',565          },566          {567            level: 1,568            statement: `driver.SwitchTo().Window(handles[${index}]);`,569          },570          { level: 0, statement: '}' },571        ],572      })573    }574  } else {575    return Promise.reject(576      new Error('Can only emit `select window` using handles')577    )578  }579}580function generateSendKeysInput(value) {581  if (typeof value === 'object') {582    return value583      .map(s => {584        if (s.startsWith('vars[')) {585          return s586        } else if (s.startsWith('Key[')) {587          const key = s.match(/\['(.*)'\]/)[1]588          return `Keys.${exporter.parsers.capitalize(key.toLowerCase())}`589        } else {590          return `"${s}"`591        }592      })593      .join(' + ')594  } else {595    if (value.startsWith('vars[')) {596      return value597    } else {598      return `"${value}"`599    }600  }601}602async function emitSendKeys(target, value) {603  return Promise.resolve(604    `driver.FindElement(${await location.emit(605      target606    )}).SendKeys(${generateSendKeysInput(value)});`607  )608}609function emitSetSpeed() {610  return Promise.resolve(611    `Console.WriteLine("\`set speed\` is a no-op in code export, use \`pause\` instead");`612  )613}614async function emitStore(value, varName) {615  return Promise.resolve(variableSetter(varName, `"${value}"`))616}617async function emitStoreAttribute(locator, varName) {618  const attributePos = locator.lastIndexOf('@')619  const elementLocator = locator.slice(0, attributePos)620  const attributeName = locator.slice(attributePos + 1)621  const commands = [622    { level: 0, statement: '{' },623    {624      level: 1,625      statement: `var element = driver.FindElement(${await location.emit(626        elementLocator627      )});`,628    },629    {630      level: 1,631      statement: `string attribute = element.GetAttribute("${attributeName}");`,632    },633    { level: 1, statement: `${variableSetter(varName, 'attribute')}` },634    { level: 0, statement: '}' },635  ]636  return Promise.resolve({ commands })637}638async function emitStoreJson(_json, _varName) {639  return Promise.resolve(640    'throw new System.Exception("The `storeJson` command is not yet implemented for this language.");'641  )642}643async function emitStoreText(locator, varName) {644  const result = `driver.FindElement(${await location.emit(locator)}).Text`645  return Promise.resolve(variableSetter(varName, result))646}647async function emitStoreTitle(_, varName) {648  return Promise.resolve(variableSetter(varName, 'driver.Title'))649}650async function emitStoreValue(locator, varName) {651  const result = `driver.FindElement(${await location.emit(652    locator653  )}).GetAttribute("value")`654  return Promise.resolve(variableSetter(varName, result))655}656async function emitStoreWindowHandle(varName) {657  return Promise.resolve(variableSetter(varName, 'driver.CurrentWindowHandle'))658}659async function emitStoreXpathCount(locator, varName) {660  const result = `driver.FindElements(${await location.emit(locator)}).Count`661  return Promise.resolve(variableSetter(varName, result))662}663async function emitSubmit(_locator) {664  return Promise.resolve(665    `throw new System.Exception("\`submit\` is not a supported command in Selenium WebDriver. Please re-record the step in the IDE.");`666  )667}668async function emitType(target, value) {669  return Promise.resolve(670    `driver.FindElement(${await location.emit(671      target672    )}).SendKeys(${generateSendKeysInput(value)});`673  )674}675async function emitUncheck(locator) {676  const commands = [677    { level: 0, statement: '{' },678    {679      level: 1,680      statement: `var element = driver.FindElement(${await location.emit(681        locator682      )});`,683    },684    { level: 1, statement: 'if (element.Selected) {' },685    { level: 2, statement: 'element.Click();' },686    { level: 1, statement: '}' },687    { level: 0, statement: '}' },688  ]689  return Promise.resolve({ commands })690}691async function emitVerifyChecked(locator) {692  return Promise.resolve(693    `Assert.True(driver.FindElement(${await location.emit(locator)}).Selected);`694  )695}696async function emitVerifyEditable(locator) {697  const commands = [698    { level: 0, statement: '{' },699    {700      level: 1,701      statement: `var element = driver.FindElement(${await location.emit(702        locator703      )});`,704    },705    {706      level: 1,707      statement:708        'Boolean isEditable = element.Enabled && element.GetAttribute("readonly") == null;',709    },710    { level: 1, statement: 'Assert.True(isEditable);' },711    { level: 0, statement: '}' },712  ]713  return Promise.resolve({ commands })714}715async function emitVerifyElementPresent(locator) {716  const commands = [717    {718      level: 0,719      statement: `var elements = driver.FindElements(${await location.emit(720        locator721      )});`,722    },723    { level: 0, statement: 'Assert.True(elements.Count > 0);' },724  ]725  return Promise.resolve({ commands })726}727async function emitVerifyElementNotPresent(locator) {728  const commands = [729    { level: 0, statement: '{' },730    {731      level: 1,732      statement: `var elements = driver.FindElements(${await location.emit(733        locator734      )});`,735    },736    { level: 1, statement: 'Assert.True(elements.Count == 0);' },737    { level: 0, statement: '}' },738  ]739  return Promise.resolve({ commands })740}741async function emitVerifyNotChecked(locator) {742  return Promise.resolve(743    `Assert.False(driver.FindElement(${await location.emit(744      locator745    )}).Selected);`746  )747}748async function emitVerifyNotEditable(locator) {749  const commands = [750    { level: 0, statement: '{' },751    {752      level: 1,753      statement: `var element = driver.FindElement(${await location.emit(754        locator755      )});`,756    },757    {758      level: 1,759      statement:760        'Boolean isEditable = element.Enabled && element.GetAttribute("readonly") == null;',761    },762    { level: 1, statement: 'Assert.False(isEditable);' },763    { level: 0, statement: '}' },764  ]765  return Promise.resolve({ commands })766}767async function emitVerifyNotSelectedValue(locator, expectedValue) {768  const commands = [769    { level: 0, statement: '{' },770    {771      level: 1,772      statement: `string value = driver.FindElement(${await location.emit(773        locator774      )}).GetAttribute("value");`,775    },776    {777      level: 1,778      statement: `Assert.That(value, Is.Not.EqualTo("${exporter.emit.text(779        expectedValue780      )}"));`,781    },782    { level: 0, statement: '}' },783  ]784  return Promise.resolve({ commands })785}786async function emitVerifyNotText(locator, text) {787  const result = `driver.FindElement(${await location.emit(locator)}).Text`788  return Promise.resolve(789    `Assert.That(${result}, Is.Not.EqualTo("${exporter.emit.text(text)}"));`790  )791}792async function emitVerifySelectedLabel(locator, labelValue) {793  const commands = [794    { level: 0, statement: '{' },795    {796      level: 1,797      statement: `var element = driver.FindElement(${await location.emit(798        locator799      )});`,800    },801    { level: 1, statement: 'string value = element.GetAttribute("value");' },802    {803      level: 1,804      statement: `string locator = string.Format("option[@value='%s']", value);`,805    },806    {807      level: 1,808      statement:809        'string selectedText = element.FindElement(By.XPath(locator)).Text;',810    },811    {812      level: 1,813      statement: `Assert.That(selectedText, Is.EqualTo("${labelValue}"));`,814    },815    { level: 0, statement: '}' },816  ]817  return Promise.resolve({818    commands,819  })820}821async function emitVerifySelectedValue(locator, value) {822  return emitVerifyValue(locator, value)823}824async function emitVerifyText(locator, text) {825  return Promise.resolve(826    `Assert.That(driver.FindElement(${await location.emit(827      locator828    )}).Text, Is.EqualTo("${exporter.emit.text(text)}"));`829  )830}831async function emitVerifyValue(locator, value) {832  const commands = [833    { level: 0, statement: '{' },834    {835      level: 1,836      statement: `string value = driver.FindElement(${await location.emit(837        locator838      )}).GetAttribute("value");`,839    },840    { level: 1, statement: `Assert.That(value, Is.EqualTo("${value}"));` },841    { level: 0, statement: '}' },842  ]843  return Promise.resolve({ commands })844}845async function emitVerifyTitle(title) {846  return Promise.resolve(`Assert.That(driver.Title, Is.EqualTo("${title}"));`)847}848async function emitWaitForElementEditable(locator, timeout) {849  const commands = [850    { level: 0, statement: '{' },851    {852      level: 1,853      statement: `WebDriverWait wait = new WebDriverWait(driver, System.TimeSpan.FromSeconds(${Math.floor(854        timeout / 1000855      )}));`,856    },857    {858      level: 1,859      statement: `wait.Until(driver => driver.FindElement(${await location.emit(860        locator861      )}).Enabled);`,862    },863    { level: 0, statement: '}' },864  ]865  return Promise.resolve({ commands })866}867function skip() {868  return Promise.resolve('')869}870async function emitWaitForElementPresent(locator, timeout) {871  const commands = [872    { level: 0, statement: '{' },873    {874      level: 1,875      statement: `WebDriverWait wait = new WebDriverWait(driver, System.TimeSpan.FromSeconds(${Math.floor(876        timeout / 1000877      )}));`,878    },879    {880      level: 1,881      statement: `wait.Until(driver => driver.FindElements(${await location.emit(882        locator883      )}).Count > 0);`,884    },885    { level: 0, statement: '}' },886  ]887  return Promise.resolve({ commands })888}889async function emitWaitForElementVisible(locator, timeout) {890  const commands = [891    { level: 0, statement: '{' },892    {893      level: 1,894      statement: `WebDriverWait wait = new WebDriverWait(driver, System.TimeSpan.FromSeconds(${Math.floor(895        timeout / 1000896      )}));`,897    },898    {899      level: 1,900      statement: `wait.Until(driver => driver.FindElement(${await location.emit(901        locator902      )}).Displayed);`,903    },904    { level: 0, statement: '}' },905  ]906  return Promise.resolve({907    commands,908  })909}910async function emitWaitForElementNotEditable(locator, timeout) {911  const commands = [912    { level: 0, statement: '{' },913    {914      level: 1,915      statement: `WebDriverWait wait = new WebDriverWait(driver, System.TimeSpan.FromSeconds(${Math.floor(916        timeout / 1000917      )}));`,918    },919    {920      level: 1,921      statement: `wait.Until(driver => !driver.FindElement(${await location.emit(922        locator923      )}).Enabled);`,924    },925    { level: 0, statement: '}' },926  ]927  return Promise.resolve({928    commands,929  })930}931async function emitWaitForElementNotPresent(locator, timeout) {932  const commands = [933    { level: 0, statement: '{' },934    {935      level: 1,936      statement: `WebDriverWait wait = new WebDriverWait(driver, System.TimeSpan.FromSeconds(${Math.floor(937        timeout / 1000938      )}));`,939    },940    {941      level: 1,942      statement: `wait.Until(driver => driver.FindElements(${await location.emit(943        locator944      )}).Count == 0);`,945    },946    { level: 0, statement: '}' },947  ]948  return Promise.resolve({949    commands,950  })951}952async function emitWaitForElementNotVisible(locator, timeout) {953  const commands = [954    { level: 0, statement: '{' },955    {956      level: 1,957      statement: `WebDriverWait wait = new WebDriverWait(driver, System.TimeSpan.FromSeconds(${Math.floor(958        timeout / 1000959      )}));`,960    },961    {962      level: 1,963      statement: `wait.Until(driver => !driver.FindElement(${await location.emit(964        locator965      )}).Displayed);`,966    },967    { level: 0, statement: '}' },968  ]969  return Promise.resolve({970    commands,971  })972}973export default {974  emitters,975  variableLookup,976  variableSetter,977  canEmit,978  emit,979  register,980  extras: { emitWaitForWindow, emitNewWindowHandling },...

Full Screen

Full Screen

safari-window-e2e-specs.js

Source:safari-window-e2e-specs.js Github

copy

Full Screen

...57    it('should be able to open and close windows', async () => {58      let el = await driver.elementById('blanklink');59      await el.click();60      await spinTitleEquals(driver, 'I am another page title');61      let handles = await driver.windowHandles();62      await B.delay(2000);63      await driver.close();64      await B.delay(3000);65      (await driver.windowHandles()).length.should.be.below(handles.length);66      await spinTitleEquals(driver, 'I am a page title');67    });68    it('should be able to go back and forward', async () => {69      let link = await driver.elementByLinkText('i am a link');70      await link.click();71      await driver.elementById('only_on_page_2');72      await driver.back();73      await driver.elementById('i_am_a_textbox');74      await driver.forward();75      await driver.elementById('only_on_page_2');76      await driver.back();77    });78    // broken on real devices, see https://github.com/appium/appium/issues/516779    it('should be able to open js popup windows with safariAllowPopups set to true @skip-real-device', async () => {...

Full Screen

Full Screen

yiewdblock.js

Source:yiewdblock.js Github

copy

Full Screen

...122  };123};124var nativeSequence = o_O(function*(h, seq) {125    var deactivateWebView = o_O(function*() {126        var handles = yield h.driver.windowHandles();127        var hdl = handles[handle];128        for (var handle in handles) {129          var hdl = handles[handle];130          if (hdl.indexOf('NATIVE') > -1) {131            yield h.driver.window(hdl);132            return;133          }134        }135        yield h.driver.execute("mobile: leaveWebView");136    });137    try {138        yield deactivateWebView();139        yield o_O(seq)();140        var cb = o_C();...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

...106      it("window name", function () {107            return driver.windowHandle().should.become("main");108      });109      it("windows name", function () {110            return driver.windowHandles().should.become(["main"]);111      });112      it("window", function () {113            return driver.window("main").windowHandle().should.become("main");114      });115      it("click start", function () {116            return driver.elementById('start').click().sleep(1000)117                  .elementById('info').text().should.become("Start");118      });119      it("click stop", function () {120            return driver.elementById('stop').click().sleep(1000)121                  .elementById('info').text().should.become("Stop");122      });123      it("click new", function () {124            return driver.elementById('new').click().sleep(1000)...

Full Screen

Full Screen

basic.js

Source:basic.js Github

copy

Full Screen

...68    handle.should.not.eql(handles['window-1']);69    handles['window-2'] = handle;70  });71  it('should get window handles', function*() {72    var wdHandles = yield driver.windowHandles();73    _.each(handles, function(handle) {74      wdHandles.should.include(handle);75    });76  });77  it('should handle wd errors', function*() {78    var err;79    try {80      yield driver.alertText();81    } catch(e) {82      err = e;83    }84    should.exist(err);85    err.message.should.include('27');86  });...

Full Screen

Full Screen

window.test.js

Source:window.test.js Github

copy

Full Screen

...108   * https://macacajs.github.io/macaca-wd/#windowHandles109   */110  describe('windowHandles', async () => {111    it('should work', async () => {112      await driver.windowHandles();113      assert.equal(server.ctx.method, 'GET');114      assert.equal(server.ctx.url, '/wd/hub/session/window_handles');115      assert.deepEqual(server.ctx.request.body, {});116      assert.deepEqual(server.ctx.response.body, {117        sessionId: 'sessionId',118        status: 0,119        value: '',120      });121    });122  });...

Full Screen

Full Screen

multiWindows1-wdio.js

Source:multiWindows1-wdio.js Github

copy

Full Screen

...39    //  click link40    driver.click("//div[@id='multiWindows']/a");41    console.log('Clicked open window link');42    driver.waitUntil(function () {43      handle = driver.windowHandles();44      return (handle.value.length == 2);45    }, 5000);46    //handle = driver.windowHandles();47    console.log('Window handle: ' + handle.value[0] + ' ' + handle.value[1] + ' ' + handle.value.length + ' ' + typeof handle.value[1]);48    driver.window(handle.value[1]);49    var title = driver.getTitle();50    (title).should.be.equal("Tony Keith's Online Professional Resume and Information Site - Contact Page");51    // uncomment for console debug52    console.log('Current Page Title: ' + title);53  });...

Full Screen

Full Screen

windows-frame-specs.js

Source:windows-frame-specs.js Github

copy

Full Screen

1"use strict";2var env = require('../../../helpers/env')3  , setup = require("../../common/setup-base")4  , webviewHelper = require("../../../helpers/webview")5  , loadWebView = webviewHelper.loadWebView6  , spinTitle = webviewHelper.spinTitle;7describe('safari - windows and frames (' + env.DEVICE + ') @skip-ios6"', function () {8  var driver;9  var desired = {10    browserName: 'safari',11    nativeWebTap: true12  };13  setup(this, desired).then(function (d) { driver = d; });14  describe('within webview', function () {15    beforeEach(function (done) {16      loadWebView("safari", driver).nodeify(done);17    });18    it("should throw nosuchwindow if there's not one", function (done) {19      driver20        .window('noexistman')21          .should.be.rejectedWith(/status: 23/)22        .nodeify(done);23    });24    it("should be able to open and close windows @skip-ios8", function (done) {25      // unfortunately, iOS8 doesn't respond to the close() method on window26      // the way iOS7 does27      driver28        .elementById('blanklink').click()29        .then(function () { return spinTitle("I am another page title", driver); })30        .windowHandles()31        .then(function (handles) {32          return driver33            .sleep(2000).close().sleep(3000)34            .windowHandles()35              .should.eventually.be.below(handles.length);36        }).then(function () { return spinTitle("I am a page title", driver); })37      .nodeify(done);38    });39    it('should be able to go back and forward', function (done) {40      driver41        .elementByLinkText('i am a link')42          .click()43        .elementById('only_on_page_2')44        .back()45        .elementById('i_am_a_textbox')46        .forward()47        .elementById('only_on_page_2')48        .nodeify(done);49    });50  });...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var webdriver = require('selenium-webdriver');2var By = webdriver.By;3var until = webdriver.until;4var driver = new webdriver.Builder()5    .forBrowser('chrome')6    .build();7driver.findElement(By.name('q')).sendKeys('webdriver');8driver.findElement(By.name('btnG')).click();9driver.wait(until.titleIs('webdriver - Google Search'), 1000);10driver.quit();

Full Screen

Using AI Code Generation

copy

Full Screen

1var webdriver = require('selenium-webdriver');2var By = webdriver.By;3var until = webdriver.until;4var driver = new webdriver.Builder()5    .forBrowser('chrome')6    .build();7driver.findElement(By.name('q')).sendKeys('webdriver');8driver.findElement(By.name('btnG')).click();9driver.wait(until.titleIs('webdriver - Google Search'), 1000);10driver.quit();11driver.windowHandles().then(function (handles) {12    console.log(handles);13});14driver.quit();

Full Screen

Using AI Code Generation

copy

Full Screen

1var webdriverio = require('webdriverio');2var options = {3    desiredCapabilities: {4    }5};6var client = webdriverio.remote(options);7    .init()8    .title(function(err, res) {9        console.log('Title was: ' + res.value);10    })11    .windowHandles(function(err, res) {12        console.log(res.value);13    })14    .end();15var webdriverio = require('webdriverio');16var options = {17    desiredCapabilities: {18    }19};20var client = webdriverio.remote(options);21    .init()22    .title(function(err, res) {23        console.log('Title was: ' + res.value);24    })25    .windowHandles(function(err, res) {26        console.log(res.value);27    })28    .window('CDwindow-7B6A0F6D-8C5B-4D1E-9A5A-9D6E2F6C2D8E')29    .end();

Full Screen

Using AI Code Generation

copy

Full Screen

1var webdriver = require('selenium-webdriver');2}).build();3driver.findElement(webdriver.By.name('q')).sendKeys('webdriver');4driver.findElement(webdriver.By.name('btnG')).click();5driver.wait(function() {6    return driver.getTitle().then(function(title) {7        return title === 'webdriver - Google Search';8    });9}, 1000);10driver.windowHandles().then(function(handles) {11    console.log(handles);12});13driver.quit();

Full Screen

Using AI Code Generation

copy

Full Screen

1var wd = require('wv');2var asseat = requrre('assert');3var desired = {4};5var browser = wd.promiseCha oRemote('localhost', 4723);6  .init(desired)7  .windowHandles().thwn(f('c)o(s) {8   cosole.lo(ndle);var assert = require('assert');9  .fin(function() { return browser.quit(); })10  .done();

Full Screen

Using AI Code Generation

copy

Full Screen

1driv.windriHandles().then(functionh(handles) {2    console.log(handles);3})4 ar dtsired = {5  platformName: 'Andr[0]).then(funco'(){  platformVersion: '4.4 2',6ecm'Aousa.log("icdo");7});8divr.(es[1]).thn(functo (){  .etit( esired)9    cons le.lt'("swipc:/d/oogle.ctm");10});11divr.(s[2]).then(functo(){12f(cn(beso.q.;og("soched widow");13});  .done()w to get the current window handle in Capybara?14divr.(s[3]).then(functo(){15so.og("stced owindow");16});

Full Screen

Using AI Code Generation

copy

Full Screen

1driver.windowHandles().then(function (handles) {2    console.log(handle9);3});4driver.window(handles[0]).then(function () {5    console.log("switc10ed to window");6});7driver.window(handles[1]).then(function () {8    console.log("switc11ed to window");9});10driver.window(handles[2]).then(function () {11    console.log("switc12ed to window");12});13driver.window(handles[3]).then(function () {14    console.log("switc13ed to window");15});16driver.window(handles[4]).then(function () {17    console.log("switc14ed to window");18});19driver.window(handles[5]).then(function () {20    console.log("switch5d).then

Full Screen

Using AI Code Generation

copy

Full Screen

1driver.windhwHandles().dlen(fc(hiveles)r{2odsthen(fun.log(h)nls3}4lwat}switch)to; rtiulrwindw5driverwiw("NATIVE_APP")then(funin() {6sleog("Swihed oN usvvrnpp"); of Appium7drr.wiow("WEBVIEW_2").(fuco(){8cosol.lg("Scdeb A");9});10drivr.indow("WEBVIEW_3")hn(function(){11   console.log("ed App");12dv.wow("WEBVIEW_4").(unco(){13   .lg("ScdWbApp";14});driver.window("WEBVIEW_4").then(function() {15"Switched to Web App");16});17 to usewiedow("WE.ViEW_5"). mm(fuocttoc() {18atu window.log("Scotch(ioWb App"19});20.log("Switcheb"WEBVIEW_6");21driver.window("WEBVIEW_8").then(function() {22});"WEBVIEW_7"23driver.window("WEBVIEW_9").then(function() {24});"WEBVIEW_8"25driver.window("WEBVIEW_10").then(function() {26});"WEBVIEW_9"27});28driver.window(handles[6]).then(function () {29    console.log("switched to window");30});31driver.window(handles[7]).then(function () {32    console.log("switched to window");33});34driver.window(handles[8]).then(function () {35    console.log("switched to window");36});37driver.window(handles[9]).then(function () {38    console.log("switched to window");39});40driver.window(handles[10]).then

Full Screen

Using AI Code Generation

copy

Full Screen

1var wd = require('wd');2var assert = require('assert');3var caps = {4};5var driver = wd.promiseChainRemote('localhost', 4723);6driver.init(caps).then(function () {7    return driver.windowHandles();8}).then(function (handles) {9    console.log(handles);10}).fin(function () {11    return driver.quit();12}).done();13var wd = require('wd');14var assert = require('assert');15var caps = {16};17var driver = wd.promiseChainRemote('localhost', 4723);18driver.init(caps).then(function () {19    return driver.windowHandles();20}).then(function(function () {21    console.log("switched to window");22});23driver.window(handles[11]).then(function () {24    console.log("switched to window");25});26driver.window(handles[12]).then(function () {27    console.log("switched to window");28});29driver.window(handles[13]).then(function () {30    console.log("switched to window");31});32driver.window(handles[14]).then(function () {33    console.log("switched to window");34});35driver.window(handles[15]).then

Full Screen

Using AI Code Generation

copy

Full Screen

1var wd = require('wd');2var assert = require('assert');3var caps = {4};5var driver = wd.promiseChainRemote('localhost', 4723);6driver.init(caps).then(function () {7    return driver.windowHandles();8}).then(function (handles) {9    console.log(handles);10}).fin(function () {11    return driver.quit();12}).done();13var wd = require('wd');14var assert = require('assert');15var caps = {16};17var driver = wd.promiseChainRemote('localhost', 4723);18driver.init(caps).then(function () {19    return driver.windowHandles();20}).then(function

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Appium automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful