Álvaro N. Franz
Álvaro N. Franz

Reputation: 1228

Python and Selenium - Disable alert when leaving page

Using Python 3 and Chromedriver.

Suppose an automated python program is surfing the web, fetching stuff from different sources.

Suppose any of those websites fires an "Are you sure you wanna leave this page?" alert.

Key word: any (in a random way) of those websites.

Question:

How may I set up the program to handle those alerts, by always saying: "yes, i want to leave this page".?

--- UPDATE ---

Possible approach:

Based on the comment below I am now doing:

def super_get(url):
    driver.get(url)
    driver.execute_script("window.onbeforeunload = function() {};")

And now use super_get() insetad of the standard driver.get()

Can you think of any more efficient or cleaner way of doing it?

Upvotes: 5

Views: 6963

Answers (2)

Bruce
Bruce

Reputation: 1

Goal Get all listeners by getEventListeners(window)['beforeunload'] and remove them all.

Step1. Put DOMDebugger.getEventListeners to window['getEventListeners']

VB.NET

Dim myChromeDriver as ChromeDriver = getMyDriver()
myChromeDriver.ExecuteChromeCommand("Runtime.evaluate", New Dictionary(Of String, Object)() From {
{"expression", "window['getEventListeners'] = getEventListeners;"},
{"includeCommandLineAPI", True}})

We don't need the result value of this Command.

includeCommandLineAPI=True is required or it will throw exception because getEventListeners is an CommandLineAPI that is undefined in script execution context

Step2. Remove all listeners

Dim jsCmd As String = "var eventlistener = window['getEventListeners'](window)['beforeunload'][0];" &
"    window.removeEventListener('beforeunload', " &
"    eventlistener.listener, " &
"    eventlistener.useCapture); "
myChromeDriver.ExecuteScript(jsCmd)

Run this script until getEventListeners(window)['beforeunload'] is empty.

This script will throw exception when all listeners removed, you can fix it.

Finally

oDriver.Navigate.GoToUrl("https://www.google.com")

The "Are you sure.." alert should disappear.

Upvotes: 0

Álvaro N. Franz
Álvaro N. Franz

Reputation: 1228

Disable the alert on before unload:

def super_get(url):
    driver.get(url)
    driver.execute_script("window.onbeforeunload = function() {};")

And now use super_get(whatever_url) insetad of the standard driver.get(whatever_url)

Disable all alerts in page:

def super_get(url):
    driver.get(url)
    driver.execute_script("window.alert = function() {};")

Hope it helps somebody. Cheers.

Upvotes: 6

Related Questions