Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Feign focus in Selenium chrome browser

I'm using Selenium to scrape data from a website. The website requires window focus in order to display certain elements that I need.

I want to be able to run my program in the background, without having to focus the window while it's running.

Is there any way to trick the site into thinking it's focused on?

I'm using the selenium chrome driver.


Edit: Here's a quick and dirty test I built.

Check out the code on GitHub

The website background color will turn black when the window.onblur event is recieved, and turn back white when the window.onfocus event is recieved.

I want to fake those events, to make the browser think it's recieved a focus event.

like image 409
Anubian Noob Avatar asked Apr 19 '15 19:04

Anubian Noob


1 Answers

Since the page gets focus information through the onfocus and onblur callbacks in the window object, you can just call them yourself.

browser.execute_script("window.onfocus()")
browser.execute_script("window.onblur()")

For fun, try this script out:

from selenium import webdriver
import time

chromedriver = "./chromedriver"
browser = webdriver.Chrome(executable_path = chromedriver)

browser.get('http://anubiann00b.github.io/FocusTest/')

while True:
    browser.execute_script("window.onfocus()")
    time.sleep(1)
    browser.execute_script("window.onblur()")
    time.sleep(1)

And of course, if you want to make the browser think it's always focused, make the onblur method call the onfocus method:

browser.execute_script("window.onblur = function() { window.onfocus() }")
like image 60
Anubian Noob Avatar answered Oct 02 '22 13:10

Anubian Noob