跳至主要內容

switchFrame

將目前的執行環境切換到框架,例如頁面上的 iframe。有多種方法可以在頁面上查詢框架

  • 如果給定一個字串,它會切換到具有匹配的環境 ID、URL 或包含該字串的 URL 的框架

    // switch to a frame that has a specific url or contains a string in the url
    await browser.url('https://www.w3schools.com/tags/tryit.asp?filename=tryhtml_iframe')
    // Note: this frame is located in a nested iframe, however you only need to provide
    // the frame url of your desired frame
    await browser.switchFrame('https://www.w3schools.com')
    // check the title of the page
    console.log(await browser.execute(() => [document.title, document.URL]))
    // outputs: [ 'W3Schools Online Web Tutorials', 'https://www.w3schools.com/' ]
  • 如果您有框架的環境 ID,您可以直接使用它

    // switch to a frame that has a certain context id
    await browser.switchFrame('A5734774C41F8C91D483BDD4022B2EF3')
  • 如果給定一個引用 iframe 元素的 WebdriverIO 元素,它將切換到該框架

    // switch to a frame element queried from current context
    await browser.switchFrame($('iframe'))
  • 如果給定一個函數,它將循環遍歷頁面上的所有 iframe,並在環境物件中呼叫該函數。該函數應返回一個布林值,指示是否應選取該框架。該函數將在瀏覽器中執行,並允許存取所有 Web API,例如

    // switch to first frame that contains an element with id "#frameContent"
    await browser.switchFrame(() => Boolean(document.querySelector('#frameContent')))
    // switch to first frame that contains "webdriver" in the URL
    await browser.switchFrame(() => document.URL.includes('webdriver'))
  • 如果給定 null,它將切換到最上層的框架

    // first switch into a frame
    await browser.switchFrame($('iframe'))
    // do more automation within that frame, then ...

    // switch to the top level frame
    await browser.switchFrame(null)

一旦您切換到框架,所有進一步的指令都將在該框架的環境中執行,包括導航到不同的頁面。

用法
browser.switchFrame(context)
參數
名稱類型詳細資訊
contextstringobjectfunction

歡迎!我能幫上什麼忙嗎?

WebdriverIO AI Copilot