Clicks an element using pure JS. Does not use jQuery.
(self, selector, by="css selector")
| 14333 | ############ |
| 14334 | |
| 14335 | def __js_click(self, selector, by="css selector"): |
| 14336 | """Clicks an element using pure JS. Does not use jQuery.""" |
| 14337 | selector, by = self.__recalculate_selector(selector, by) |
| 14338 | css_selector = self.convert_to_css_selector(selector, by=by) |
| 14339 | css_selector = re.escape(css_selector) # Add "\\" to special chars |
| 14340 | css_selector = self.__escape_quotes_if_needed(css_selector) |
| 14341 | is_visible = self.is_element_visible(selector, by=by) |
| 14342 | current_url = self.get_current_url() |
| 14343 | script = ( |
| 14344 | """var simulateClick = function (elem) { |
| 14345 | var evt = new MouseEvent('click', { |
| 14346 | bubbles: true, |
| 14347 | cancelable: true, |
| 14348 | view: window |
| 14349 | }); |
| 14350 | var canceled = !elem.dispatchEvent(evt); |
| 14351 | }; |
| 14352 | var someLink = document.querySelector('%s'); |
| 14353 | simulateClick(someLink);""" |
| 14354 | % css_selector |
| 14355 | ) |
| 14356 | if getattr(self, "recorder_mode", None): |
| 14357 | self.save_recorded_actions() |
| 14358 | try: |
| 14359 | self.execute_script(script) |
| 14360 | except Exception as e: |
| 14361 | # If element was visible but no longer, or on a different page now, |
| 14362 | # assume that the click actually worked and continue with the test. |
| 14363 | if ( |
| 14364 | (is_visible and not self.is_element_visible(selector, by=by)) |
| 14365 | or current_url != self.get_current_url() |
| 14366 | ): |
| 14367 | return # The click worked, but threw an Exception. Keep going. |
| 14368 | # It appears the first click didn't work. Make another attempt. |
| 14369 | self.wait_for_ready_state_complete() |
| 14370 | if "Cannot read properties of null" in e.msg: |
| 14371 | page_actions.wait_for_element_present( |
| 14372 | self.driver, selector, by, timeout=5 |
| 14373 | ) |
| 14374 | if not page_actions.is_element_clickable( |
| 14375 | self.driver, selector, by |
| 14376 | ): |
| 14377 | with suppress(Exception): |
| 14378 | self.wait_for_element_clickable( |
| 14379 | selector, by, timeout=1.8 |
| 14380 | ) |
| 14381 | # If the regular mouse-simulated click fails, do a basic JS click |
| 14382 | script = ( |
| 14383 | """document.querySelector('%s').click();""" |
| 14384 | % css_selector |
| 14385 | ) |
| 14386 | self.execute_script(script) |
| 14387 | |
| 14388 | def __js_click_element(self, element): |
| 14389 | """Clicks an element using pure JS. Does not use jQuery.""" |
no test coverage detected