0

I'm crawlling some web pages for my research. I want to inject javascript code below when redirecting to other page:

window.alert = function() {};

I tried to inject the javascript code below using WebDriverWait, so that selenium may execute the code as soon as the driver redirect to new page. But It doesn't work.

while (some conditions) :
  try:
    WebDriverWait(browser, 5).until(
                lambda driver: original_url != browser.current_url)
    browser.execute_script("window.alert = function() {};")
  except:
    //do sth


  original_url = browser.current_url

It seems that the driver execute javascript code after the page loaded because the alert that made in the redirected page is showing.

tonynamy
  • 29
  • 1
  • 5

2 Answers2

1

Chrome 14+ blocks alerts inside onunload (https://stackoverflow.com/a/7080331/3368011)

But, I think the following questions may help you:

Chootti
  • 357
  • 3
  • 15
  • I tried it just now. I replaced "window.alert = function() {};" to "window.onbeforeunload = function(){ window.alert = function() {};}". But unfortunately as I referred, it seems that the javascript code injects after the page's javascript loaded. The page's alert showing again. – tonynamy Jul 23 '19 at 09:02
  • I think you don't need the whole code. I mean you don't need to make web driver wait. Just use: ```browser.execute_script("window.alert = function() {};")``` – Chootti Jul 23 '19 at 10:13
  • The reason why I posted this question is that the executed javascript code is useless after redirecting to other page. It works well if I stay in one page, but if the page redirects using location.href or else, it doesn't last. So that's why I made the web driver wait until redirecting, and execute ```browser.execute_script("window.alert = function() {};")``` – tonynamy Jul 23 '19 at 10:36
  • I understand what you mean, I have found several ways but not sure tho. – Chootti Jul 23 '19 at 11:18
  • Have you tried onHashChange event? https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onhashchange – Chootti Jul 24 '19 at 05:43
  • Thanks for your concern, Chootti. I also tried that but didn't work properly. :( I think the script executes after redirection. I solved my problem in other way, please see my self-answer. – tonynamy Aug 04 '19 at 15:21
1

I solved my problem in other way. I tried and tried again with browser.switch_to_alert but it didn't work. Then I found that it was deprecated, so not works correctly. I checked the alert and dismiss it in every 1 second with following code :

while *some_condition* :
        try:
            Alert(browser).dismiss()
        except:
            print("no alert")
            continue

This works very fine, in Windows 10, python 3.7.4

tonynamy
  • 29
  • 1
  • 5