防止 onbeforeunload 对话框干扰测试

Prevent onbeforeunload dialog from interfering with tests

我希望在 Capybara 启动的 Chrome 实例中禁用从 onbeforeunload 生成的对话框。我有一个非常大的测试套件,修改每个 visit/refresh 以包含单击“离开”确认的代码是不切实际的。

我试过在访问和刷新之前添加 page.execute_script ‘window.onbeforeunload = undefined;’,虽然这行得通,但它也有一个问题,那就是必须修改我所有的访问和刷新调用。

我还检查了是否有任何 Chrome CLI 选项我可以添加以禁用此功能,但我没有找到任何相关的东西。我在这里查看:https://peter.sh/experiments/chromium-command-line-switches/ 但在搜索卸载、警报和对话框后,没有匹配的内容似乎相关。

我正在使用 Chrome驱动程序 v2.33、Chrome 62、Capybara 2.5 和 Selenium-webdriver 2.53.4。如果需要,将使用更多信息更新此 post。

这可能吗?

要让水豚 visitrefresh 方法总是首先调用您的 execute_script 最简单的解决方案是

module BeforeUnloadDisabler
  def visit(*args)
    execute_script 'window.onbeforeunload = undefined;'
    super
  end

  def refresh(*args)
    execute_script 'window.onbeforeunload = undefined;'
    super
  end
end

::Capybara::Session.prepend(BeforeUnloadDisabler)

尽管如此,如果您的应用程序在卸载前注册警报那么多,您可能想要重新考虑您的设计选择——这对用户来说真的很烦人。