Best Python code snippet using SeleniumBase
js_utils.py
Source:js_utils.py
...163 string = string.replace("'", "\\'")164 if string.count('"') != string.count('\\"'):165 string = string.replace('"', '\\"')166 return string167def safe_execute_script(driver, script):168 """ When executing a script that contains a jQuery command,169 it's important that the jQuery library has been loaded first.170 This method will load jQuery if it wasn't already loaded. """171 try:172 driver.execute_script(script)173 except Exception:174 # The likely reason this fails is because: "jQuery is not defined"175 activate_jquery(driver) # It's a good thing we can define it here176 driver.execute_script(script)177def wait_for_css_query_selector(178 driver, selector, timeout=settings.SMALL_TIMEOUT):179 element = None180 start_ms = time.time() * 1000.0181 stop_ms = start_ms + (timeout * 1000.0)182 for x in range(int(timeout * 10)):183 try:184 selector = re.escape(selector)185 selector = escape_quotes_if_needed(selector)186 element = driver.execute_script(187 """return document.querySelector('%s')""" % selector)188 if element:189 return element190 except Exception:191 element = None192 if not element:193 now_ms = time.time() * 1000.0194 if now_ms >= stop_ms:195 break196 time.sleep(0.1)197 raise Exception(198 "Element {%s} was not present after %s seconds!" % (199 selector, timeout))200def highlight_with_js(driver, selector, loops, o_bs):201 script = ("""document.querySelector('%s').style.boxShadow =202 '0px 0px 6px 6px rgba(128, 128, 128, 0.5)';"""203 % selector)204 try:205 driver.execute_script(script)206 except Exception:207 return208 for n in range(loops):209 script = ("""document.querySelector('%s').style.boxShadow =210 '0px 0px 6px 6px rgba(255, 0, 0, 1)';"""211 % selector)212 driver.execute_script(script)213 time.sleep(0.0181)214 script = ("""document.querySelector('%s').style.boxShadow =215 '0px 0px 6px 6px rgba(128, 0, 128, 1)';"""216 % selector)217 driver.execute_script(script)218 time.sleep(0.0181)219 script = ("""document.querySelector('%s').style.boxShadow =220 '0px 0px 6px 6px rgba(0, 0, 255, 1)';"""221 % selector)222 driver.execute_script(script)223 time.sleep(0.0181)224 script = ("""document.querySelector('%s').style.boxShadow =225 '0px 0px 6px 6px rgba(0, 255, 0, 1)';"""226 % selector)227 driver.execute_script(script)228 time.sleep(0.0181)229 script = ("""document.querySelector('%s').style.boxShadow =230 '0px 0px 6px 6px rgba(128, 128, 0, 1)';"""231 % selector)232 driver.execute_script(script)233 time.sleep(0.0181)234 script = ("""document.querySelector('%s').style.boxShadow =235 '0px 0px 6px 6px rgba(128, 0, 128, 1)';"""236 % selector)237 driver.execute_script(script)238 time.sleep(0.0181)239 script = ("""document.querySelector('%s').style.boxShadow =240 '%s';"""241 % (selector, o_bs))242 driver.execute_script(script)243def highlight_with_jquery(driver, selector, loops, o_bs):244 script = """jQuery('%s').css('box-shadow',245 '0px 0px 6px 6px rgba(128, 128, 128, 0.5)');""" % selector246 safe_execute_script(driver, script)247 for n in range(loops):248 script = """jQuery('%s').css('box-shadow',249 '0px 0px 6px 6px rgba(255, 0, 0, 1)');""" % selector250 driver.execute_script(script)251 time.sleep(0.0181)252 script = """jQuery('%s').css('box-shadow',253 '0px 0px 6px 6px rgba(128, 0, 128, 1)');""" % selector254 driver.execute_script(script)255 time.sleep(0.0181)256 script = """jQuery('%s').css('box-shadow',257 '0px 0px 6px 6px rgba(0, 0, 255, 1)');""" % selector258 driver.execute_script(script)259 time.sleep(0.0181)260 script = """jQuery('%s').css('box-shadow',261 '0px 0px 6px 6px rgba(0, 255, 0, 1)');""" % selector262 driver.execute_script(script)263 time.sleep(0.0181)264 script = """jQuery('%s').css('box-shadow',265 '0px 0px 6px 6px rgba(128, 128, 0, 1)');""" % selector266 driver.execute_script(script)267 time.sleep(0.0181)268 script = """jQuery('%s').css('box-shadow',269 '0px 0px 6px 6px rgba(128, 0, 128, 1)');""" % selector270 driver.execute_script(script)271 time.sleep(0.0181)272 script = """jQuery('%s').css('box-shadow', '%s');""" % (selector, o_bs)273 driver.execute_script(script)274def add_css_link(driver, css_link):275 script_to_add_css = (276 """function injectCSS(css) {277 var head = document.getElementsByTagName("head")[0];278 var link = document.createElement("link");279 link.rel = "stylesheet";280 link.type = "text/css";281 link.href = css;282 link.crossorigin = "anonymous";283 head.appendChild(link);284 }285 injectCSS("%s");""")286 css_link = escape_quotes_if_needed(css_link)287 driver.execute_script(script_to_add_css % css_link)288def add_js_link(driver, js_link):289 script_to_add_js = (290 """function injectJS(link) {291 var body = document.getElementsByTagName("body")[0];292 var script = document.createElement("script");293 script.src = link;294 script.defer;295 script.type="text/javascript";296 script.crossorigin = "anonymous";297 script.onload = function() { null };298 body.appendChild(script);299 }300 injectJS("%s");""")301 js_link = escape_quotes_if_needed(js_link)302 driver.execute_script(script_to_add_js % js_link)303def add_css_style(driver, css_style):304 add_css_style_script = (305 """function injectStyle(css) {306 var head = document.getElementsByTagName("head")[0];307 var style = document.createElement("style");308 style.type = "text/css";309 style.appendChild(document.createTextNode(css));310 head.appendChild(style);311 }312 injectStyle("%s");""")313 css_style = css_style.replace('\n', '')314 css_style = escape_quotes_if_needed(css_style)315 driver.execute_script(add_css_style_script % css_style)316def add_js_code_from_link(driver, js_link):317 if js_link.startswith("//"):318 js_link = "http:" + js_link319 js_code = requests.get(js_link).text320 add_js_code_script = (321 '''var body = document.getElementsByTagName('body').item(0);'''322 '''var script = document.createElement("script");'''323 '''script.type = "text/javascript";'''324 '''script.onload = function() { null };'''325 '''script.appendChild(document.createTextNode("%s"));'''326 '''body.appendChild(script);''')327 js_code = js_code.replace('\n', ' ')328 js_code = escape_quotes_if_needed(js_code)329 driver.execute_script(add_js_code_script % js_code)330def add_js_code(driver, js_code):331 add_js_code_script = (332 '''var body = document.getElementsByTagName('body').item(0);'''333 '''var script = document.createElement("script");'''334 '''script.type = "text/javascript";'''335 '''script.onload = function() { null };'''336 '''script.appendChild(document.createTextNode("%s"));'''337 '''body.appendChild(script);''')338 js_code = js_code.replace('\n', ' ')339 js_code = escape_quotes_if_needed(js_code)340 driver.execute_script(add_js_code_script % js_code)341def add_meta_tag(driver, http_equiv=None, content=None):342 if http_equiv is None:343 http_equiv = "Content-Security-Policy"344 if content is None:345 content = ("default-src *; style-src 'self' 'unsafe-inline'; "346 "script-src: 'self' 'unsafe-inline' 'unsafe-eval'")347 script_to_add_meta = (348 """function injectMeta() {349 var meta = document.createElement('meta');350 meta.httpEquiv = "%s";351 meta.content = "%s";352 document.getElementsByTagName('head')[0].appendChild(meta);353 }354 injectMeta();""" % (http_equiv, content))355 driver.execute_script(script_to_add_meta)356def is_jquery_confirm_activated(driver):357 try:358 driver.execute_script("jconfirm") # Fails if jq_confirm is not defined359 return True360 except Exception:361 return False362def activate_jquery_confirm(driver):363 jquery_js = constants.JQuery.MIN_JS364 jq_confirm_css = constants.JqueryConfirm.MIN_CSS365 jq_confirm_js = constants.JqueryConfirm.MIN_JS366 if not is_jquery_activated(driver):367 add_js_link(driver, jquery_js)368 wait_for_jquery_active(driver, timeout=0.9)369 add_css_link(driver, jq_confirm_css)370 add_js_link(driver, jq_confirm_js)371 for x in range(15):372 # jQuery-Confirm needs a small amount of time to load & activate.373 try:374 driver.execute_script("jconfirm")375 wait_for_ready_state_complete(driver)376 wait_for_angularjs(driver)377 return378 except Exception:379 time.sleep(0.1)380def activate_html_inspector(driver):381 jquery_js = constants.JQuery.MIN_JS382 html_inspector_js = constants.HtmlInspector.MIN_JS383 if is_html_inspector_activated(driver):384 return385 if not is_jquery_activated(driver):386 add_js_link(driver, jquery_js)387 wait_for_ready_state_complete(driver)388 wait_for_angularjs(driver)389 wait_for_jquery_active(driver, timeout=1.5)390 add_js_link(driver, html_inspector_js)391 wait_for_ready_state_complete(driver)392 wait_for_angularjs(driver)393 for x in range(15):394 # HTML-Inspector needs a small amount of time to load & activate.395 try:396 driver.execute_script("HTMLInspector")397 wait_for_ready_state_complete(driver)398 wait_for_angularjs(driver)399 return400 except Exception:401 time.sleep(0.1)402 wait_for_ready_state_complete(driver)403 wait_for_angularjs(driver)404def activate_messenger(driver):405 jquery_js = constants.JQuery.MIN_JS406 messenger_css = constants.Messenger.MIN_CSS407 messenger_js = constants.Messenger.MIN_JS408 msgr_theme_flat_js = constants.Messenger.THEME_FLAT_JS409 msgr_theme_future_js = constants.Messenger.THEME_FUTURE_JS410 msgr_theme_flat_css = constants.Messenger.THEME_FLAT_CSS411 msgr_theme_future_css = constants.Messenger.THEME_FUTURE_CSS412 msgr_theme_block_css = constants.Messenger.THEME_BLOCK_CSS413 msgr_theme_air_css = constants.Messenger.THEME_AIR_CSS414 msgr_theme_ice_css = constants.Messenger.THEME_ICE_CSS415 spinner_css = constants.Messenger.SPINNER_CSS416 underscore_js = constants.Underscore.MIN_JS417 backbone_js = constants.Backbone.MIN_JS418 msg_style = ("Messenger.options = {'maxMessages': 8, "419 "extraClasses: 'messenger-fixed "420 "messenger-on-bottom messenger-on-right', "421 "theme: 'future'}")422 add_js_link(driver, jquery_js)423 wait_for_jquery_active(driver, timeout=0.2)424 add_css_link(driver, messenger_css)425 add_css_link(driver, msgr_theme_flat_css)426 add_css_link(driver, msgr_theme_future_css)427 add_css_link(driver, msgr_theme_block_css)428 add_css_link(driver, msgr_theme_air_css)429 add_css_link(driver, msgr_theme_ice_css)430 add_js_link(driver, underscore_js)431 add_js_link(driver, backbone_js)432 add_css_link(driver, spinner_css)433 add_js_link(driver, messenger_js)434 add_js_link(driver, msgr_theme_flat_js)435 add_js_link(driver, msgr_theme_future_js)436 from seleniumbase.core import style_sheet437 add_css_style(driver, style_sheet.messenger_style)438 for x in range(int(settings.MINI_TIMEOUT * 10.0)):439 # Messenger needs a small amount of time to load & activate.440 try:441 driver.execute_script(msg_style)442 wait_for_ready_state_complete(driver)443 wait_for_angularjs(driver)444 return445 except Exception:446 time.sleep(0.1)447def set_messenger_theme(driver, theme="default", location="default",448 max_messages="default"):449 if theme == "default":450 theme = "future"451 if location == "default":452 location = "bottom_right"453 if max_messages == "default":454 max_messages = "8"455 valid_themes = ['flat', 'future', 'block', 'air', 'ice']456 if theme not in valid_themes:457 raise Exception("Theme: %s is not in %s!" % (theme, valid_themes))458 valid_locations = (['top_left', 'top_center', 'top_right'459 'bottom_left', 'bottom_center', 'bottom_right'])460 if location not in valid_locations:461 raise Exception(462 "Location: %s is not in %s!" % (location, valid_locations))463 if location == 'top_left':464 messenger_location = "messenger-on-top messenger-on-left"465 elif location == 'top_center':466 messenger_location = "messenger-on-top"467 elif location == 'top_right':468 messenger_location = "messenger-on-top messenger-on-right"469 elif location == 'bottom_left':470 messenger_location = "messenger-on-bottom messenger-on-left"471 elif location == 'bottom_center':472 messenger_location = "messenger-on-bottom"473 elif location == 'bottom_right':474 messenger_location = "messenger-on-bottom messenger-on-right"475 msg_style = ("Messenger.options = {'maxMessages': %s, "476 "extraClasses: 'messenger-fixed %s', theme: '%s'}"477 % (max_messages, messenger_location, theme))478 try:479 driver.execute_script(msg_style)480 except Exception:481 activate_messenger(driver)482 driver.execute_script(msg_style)483 time.sleep(0.1)484def post_message(driver, message, msg_dur, style="info"):485 """ A helper method to post a message on the screen with Messenger.486 (Should only be called from post_message() in base_case.py) """487 if not msg_dur:488 msg_dur = settings.DEFAULT_MESSAGE_DURATION489 msg_dur = float(msg_dur)490 message = re.escape(message)491 message = escape_quotes_if_needed(message)492 messenger_script = ('''Messenger().post({message: "%s", type: "%s", '''493 '''hideAfter: %s, hideOnNavigate: true});'''494 % (message, style, msg_dur))495 try:496 driver.execute_script(messenger_script)497 except Exception:498 activate_messenger(driver)499 set_messenger_theme(driver)500 try:501 driver.execute_script(messenger_script)502 except Exception:503 time.sleep(0.2)504 activate_messenger(driver)505 time.sleep(0.2)506 set_messenger_theme(driver)507 time.sleep(0.5)508 driver.execute_script(messenger_script)509def post_messenger_success_message(driver, message, msg_dur):510 if not msg_dur:511 msg_dur = settings.DEFAULT_MESSAGE_DURATION512 msg_dur = float(msg_dur)513 try:514 theme = "future"515 location = "bottom_right"516 if sb_config.mobile_emulator:517 theme = "block"518 location = "top_center"519 set_messenger_theme(driver, theme=theme, location=location)520 post_message(521 driver, message, msg_dur, style="success")522 time.sleep(msg_dur + 0.07)523 except Exception:524 pass525def post_messenger_error_message(driver, message, msg_dur):526 if not msg_dur:527 msg_dur = settings.DEFAULT_MESSAGE_DURATION528 msg_dur = float(msg_dur)529 try:530 set_messenger_theme(driver, theme="block", location="top_center")531 post_message(532 driver, message, msg_dur, style="error")533 time.sleep(msg_dur + 0.07)534 except Exception:535 pass536def highlight_with_js_2(driver, message, selector, o_bs, msg_dur):537 if selector == "html":538 selector = "body"539 script = ("""document.querySelector('%s').style.boxShadow =540 '0px 0px 6px 6px rgba(128, 128, 128, 0.5)';"""541 % selector)542 try:543 driver.execute_script(script)544 except Exception:545 return546 time.sleep(0.0181)547 script = ("""document.querySelector('%s').style.boxShadow =548 '0px 0px 6px 6px rgba(205, 30, 0, 1)';"""549 % selector)550 driver.execute_script(script)551 time.sleep(0.0181)552 script = ("""document.querySelector('%s').style.boxShadow =553 '0px 0px 6px 6px rgba(128, 0, 128, 1)';"""554 % selector)555 driver.execute_script(script)556 time.sleep(0.0181)557 script = ("""document.querySelector('%s').style.boxShadow =558 '0px 0px 6px 6px rgba(50, 50, 128, 1)';"""559 % selector)560 driver.execute_script(script)561 time.sleep(0.0181)562 script = ("""document.querySelector('%s').style.boxShadow =563 '0px 0px 6px 6px rgba(50, 205, 50, 1)';"""564 % selector)565 driver.execute_script(script)566 time.sleep(0.0181)567 post_messenger_success_message(driver, message, msg_dur)568 script = ("""document.querySelector('%s').style.boxShadow =569 '%s';""" % (selector, o_bs))570 driver.execute_script(script)571def highlight_with_jquery_2(driver, message, selector, o_bs, msg_dur):572 if selector == "html":573 selector = "body"574 script = """jQuery('%s').css('box-shadow',575 '0px 0px 6px 6px rgba(128, 128, 128, 0.5)');""" % selector576 try:577 safe_execute_script(driver, script)578 except Exception:579 return580 time.sleep(0.0181)581 script = """jQuery('%s').css('box-shadow',582 '0px 0px 6px 6px rgba(205, 30, 0, 1)');""" % selector583 driver.execute_script(script)584 time.sleep(0.0181)585 script = """jQuery('%s').css('box-shadow',586 '0px 0px 6px 6px rgba(128, 0, 128, 1)');""" % selector587 driver.execute_script(script)588 time.sleep(0.0181)589 script = """jQuery('%s').css('box-shadow',590 '0px 0px 6px 6px rgba(50, 50, 200, 1)');""" % selector591 driver.execute_script(script)...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!