昨天利用了 window.open 可以開啟新分頁或視窗,今天則是來關閉多個視窗。
Nightwatch 本身其實就有 .closeWindow() 了,不過如果我們已經開啟多個視窗時,需要一個一個關掉時:
windowHandles 檢查目前共有哪些視窗switchWindow 切換視窗closeWindow 關閉視窗不過避免全部都被關掉,因為會先確定視窗數,並於最後切回原本的視窗
this.windowHandles(function(result) {
    if (result.value.length && result.value.length > 1) {
      for (let i = 1; i < result.value.length; i++) {
        this
          .switchWindow(result.value[i])
          .closeWindow()
          .acceptAlert();
      }
      this.switchWindow(result.value[0]);
    }
}
如果遇到跳出警告:

則可以使用 Nightwatch 中的 acceptAlert()/dismissAlert() 來解決。
可惜這不是可以跨瀏覽器使用的指令,在 Safari 中,這會被視為 unknow command
因次需要利用 Javascript 中 window.onbeforeunload 並設為 null
browser.execute('window.onbeforeunload = null');