Tuesday, December 3, 2013

Quick and dirty way of dealing with hover over links that works across systems.

I haven't posted in a while.  Thought I'd can post some code snippets here and there of things I ran into.

In a recent project, I had to deal with links that appear only when you hover over and area.  For example, hovering over a movie to display a pause button like in Hulu's movie player.

One problem is the ActionChains does not consistently work across all systems.  Most notably Macs and on PhantomJS.  

To get around it, I used a bit of JavaScript magic to set the element visible.

    def __force_link_visible_and_click(self, link_element):
        ActionChains(self.webdriver).move_to_element_with_offset(link_element, 1, 1).perform()
        commands = [
            "arguments[0].style.opacity = 1;", # For modern browsers
            "arguments[0].style.filter = \"alpha(opacity=100)\";" # For IE10 and earlier
        ]
        for command in commands:
            try:
                # Execute both JS commands.
                self.webdriver.execute_script(command, link_element)
            except:
                pass

        # Wait a second to allow link to become visible before clicking.
        link_element.click()

No comments: