关闭beforeonload

作者: zengde 分类: 笔记 发布时间: 2021-10-18 02:17

Chrome解决方案:--disable-popup-blocking通过ChromeOptions()使用

from selenium import webdriver

options.add_argument("--disable-popup-blocking")
driver=webdriver.Chrome(chrome_options=options, executable_path=/path/to/chromedriver')

Firefox解决方案:dom.disable_beforeunload通过FirefoxProfile()使用

from selenium import webdriver
profile = webdriver.FirefoxProfile()
profile.set_preference("dom.disable_beforeunload", True)
driver = webdriver.Firefox(firefox_profile = profile)

跨浏览器解决方案:作为跨浏览器解决方案,您可以禁用此对话框,调用executeScript()window.onbeforeunload设置为,function() {};然后可以使用以下解决方案:

driver.execute_script("window.onbeforeunload = function() {};")

基于JQuery的解决方案:

$I->executeJS( "window.onbeforeunload = null" );

补充:

<html><body>
<script>
window.onbeforeunload = function() {
    return 'You have unsaved changes!';
}
</script>
<form>
<input type='text' name='test'>
<button type='submit'>
</form>
</body></html>
driver.get("<url-to-sample-page>");
driver.close();
WebDriverWait wait = new WebDriverWait(driver, 2);
wait.until(ExpectedConditions.alertIsPresent());
driver.switchTo().alert().accept();