/
js_utils.py
1504 lines (1379 loc) 路 50 KB
/
js_utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""This module contains useful Javascript utility methods for BaseCase."""
import re
import requests
import time
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import WebDriverException
from selenium.webdriver.common.by import By
from seleniumbase import config as sb_config
from seleniumbase.config import settings
from seleniumbase.fixtures import constants
from seleniumbase.fixtures import css_to_xpath
from seleniumbase.fixtures import xpath_to_css
def wait_for_ready_state_complete(driver, timeout=settings.LARGE_TIMEOUT):
"""The DOM (Document Object Model) has a property called "readyState".
When the value of this becomes "complete", page resources are considered
fully loaded (although AJAX and other loads might still be happening).
This method will wait until document.readyState == "complete".
This may be redundant, as methods already wait for page elements to load.
If the timeout is exceeded, the test will still continue
because readyState == "interactive" may be good enough.
(Previously, tests would fail immediately if exceeding the timeout.)"""
if hasattr(settings, "SKIP_JS_WAITS") and settings.SKIP_JS_WAITS:
return
if sb_config.time_limit and not sb_config.recorder_mode:
from seleniumbase.fixtures import shared_utils
start_ms = time.time() * 1000.0
stop_ms = start_ms + (timeout * 1000.0)
for x in range(int(timeout * 10)):
if sb_config.time_limit and not sb_config.recorder_mode:
shared_utils.check_if_time_limit_exceeded()
try:
ready_state = driver.execute_script("return document.readyState;")
except WebDriverException:
# Bug fix for: [Permission denied to access property "document"]
time.sleep(0.03)
return True
if ready_state == "complete":
time.sleep(0.01) # Better be sure everything is done loading
return True
else:
now_ms = time.time() * 1000.0
if now_ms >= stop_ms:
break
time.sleep(0.1)
return False # readyState stayed "interactive" (Not "complete")
def execute_async_script(driver, script, timeout=settings.EXTREME_TIMEOUT):
driver.set_script_timeout(timeout)
return driver.execute_async_script(script)
def wait_for_angularjs(driver, timeout=settings.LARGE_TIMEOUT, **kwargs):
if hasattr(settings, "SKIP_JS_WAITS") and settings.SKIP_JS_WAITS:
return
if not settings.WAIT_FOR_ANGULARJS:
return
if timeout == settings.MINI_TIMEOUT:
timeout = settings.MINI_TIMEOUT / 2.0
NG_WRAPPER = (
"%(prefix)s"
"var $elm=document.querySelector("
"'[data-ng-app],[ng-app],.ng-scope')||document;"
"if(window.angular && angular.getTestability){"
"angular.getTestability($elm).whenStable(%(handler)s)"
"}else{"
"var $inj;try{$inj=angular.element($elm).injector()||"
"angular.injector(['ng'])}catch(ex){"
"$inj=angular.injector(['ng'])};$inj.get=$inj.get||"
"$inj;$inj.get('$browser')."
"notifyWhenNoOutstandingRequests(%(handler)s)}"
"%(suffix)s"
)
def_pre = "var cb=arguments[arguments.length-1];if(window.angular){"
prefix = kwargs.pop("prefix", def_pre)
handler = kwargs.pop("handler", "function(){cb(true)}")
suffix = kwargs.pop("suffix", "}else{cb(false)}")
script = NG_WRAPPER % {
"prefix": prefix,
"handler": handler,
"suffix": suffix,
}
try:
# This closes any pop-up alerts (otherwise the next part fails)
driver.execute_script("")
except Exception:
pass
try:
execute_async_script(driver, script, timeout=timeout)
except Exception:
time.sleep(0.05)
def convert_to_css_selector(selector, by=By.CSS_SELECTOR):
if by == By.CSS_SELECTOR:
return selector
elif by == By.ID:
return "#%s" % selector
elif by == By.CLASS_NAME:
return ".%s" % selector
elif by == By.NAME:
return '[name="%s"]' % selector
elif by == By.TAG_NAME:
return selector
elif (
by == By.XPATH
or (
selector.startswith("/")
or selector.startswith("./")
or selector.startswith("(")
)
):
return xpath_to_css.convert_xpath_to_css(selector)
elif by == By.LINK_TEXT:
return 'a:contains("%s")' % selector
elif by == By.PARTIAL_LINK_TEXT:
return 'a:contains("%s")' % selector
else:
raise Exception(
"Exception: Could not convert {%s}(by=%s) to CSS_SELECTOR!"
% (selector, by)
)
def is_html_inspector_activated(driver):
try:
driver.execute_script("HTMLInspector;") # Fails if not defined
return True
except Exception:
return False
def is_jquery_activated(driver):
try:
driver.execute_script("jQuery('html');") # Fails if jq is not defined
return True
except Exception:
return False
def wait_for_jquery_active(driver, timeout=None):
if not timeout:
timeout = 2
else:
timeout = int(timeout * 10.0)
for x in range(timeout):
# jQuery needs a small amount of time to activate.
try:
driver.execute_script("jQuery('html');")
wait_for_ready_state_complete(driver)
wait_for_angularjs(driver)
return
except Exception:
time.sleep(0.1)
def raise_unable_to_load_jquery_exception(driver):
has_csp_error = False
csp_violation = "violates the following Content Security Policy directive"
browser_logs = []
try:
browser_logs = driver.get_log("browser")
except (ValueError, WebDriverException):
pass
for entry in browser_logs:
if entry["level"] == "SEVERE":
if csp_violation in entry["message"]:
has_csp_error = True
if has_csp_error:
raise Exception(
"""Unable to load jQuery on "%s" due to a violation """
"""of the website's Content Security Policy directive. """
"""To override this policy, add "--disable-csp" on the """
"""command-line when running your tests.""" % driver.current_url
)
else:
raise Exception(
"""Unable to load jQuery on "%s" because this website may be """
"""restricting external JavaScript resources from loading."""
% driver.current_url
)
def activate_jquery(driver):
# If "jQuery is not defined" on a website, use this method to activate it.
# This method is needed because jQuery is not always defined on web sites.
try:
# Let's first find out if jQuery is already defined.
driver.execute_script("jQuery('html');")
# Since that command worked, jQuery is defined. Let's return.
return
except Exception:
# jQuery is not currently defined. Let's proceed by defining it.
pass
jquery_js = constants.JQuery.MIN_JS
add_js_link(driver, jquery_js)
for x in range(36):
# jQuery needs a small amount of time to activate.
try:
driver.execute_script("jQuery('html');")
return
except Exception:
if x == 18:
add_js_link(driver, jquery_js)
time.sleep(0.1)
# Since jQuery still isn't activating, give up and raise an exception
raise_unable_to_load_jquery_exception(driver)
def are_quotes_escaped(string):
if string.count("\\'") != string.count("'") or (
string.count('\\"') != string.count('"')
):
return True
return False
def escape_quotes_if_needed(string):
"""re.escape() works differently in Python 3.7.0 than earlier versions:
Python 3.6.5:
>>> import re
>>> re.escape('"')
'\\"'
Python 3.7.0:
>>> import re
>>> re.escape('"')
'"'
SeleniumBase needs quotes to be properly escaped for Javascript calls.
"""
if are_quotes_escaped(string):
if string.count("'") != string.count("\\'"):
string = string.replace("'", "\\'")
if string.count('"') != string.count('\\"'):
string = string.replace('"', '\\"')
return string
def is_in_frame(driver):
# Returns True if the driver has switched to a frame.
# Returns False if the driver was on default content.
in_basic_frame = driver.execute_script(
"""
var frame = window.frameElement;
if (frame) {
return true;
}
else {
return false;
}
"""
)
location_href = driver.execute_script("""return window.location.href;""")
in_external_frame = False
if driver.current_url != location_href:
in_external_frame = True
if in_basic_frame or in_external_frame:
return True
return False
def safe_execute_script(driver, script):
"""When executing a script that contains a jQuery command,
it's important that the jQuery library has been loaded first.
This method will load jQuery if it wasn't already loaded."""
try:
driver.execute_script(script)
except Exception:
# The likely reason this fails is because: "jQuery is not defined"
activate_jquery(driver) # It's a good thing we can define it here
driver.execute_script(script)
def remove_extra_slashes(selector):
if selector.count('\\"') > 0:
if selector.count('\\"') == selector.count('"'):
selector = selector.replace('\\"', '"')
elif selector.count('\\"') == selector[1:-1].count('"') and (
"'" not in selector[1:-1]
):
selector = "'" + selector[1:-1].replace('\\"', '"') + "'"
else:
pass
if selector.count("\\'") > 0:
if selector.count("\\'") == selector.count("'"):
selector = selector.replace("\\'", "'")
elif selector.count("\\'") == selector[1:-1].count("'") and (
'"' not in selector[1:-1]
):
selector = '"' + selector[1:-1].replace("\\'", "'") + '"'
else:
pass
return selector
def optimize_selector(selector):
if (len(selector) > 2 and selector[0] == "'") and (
selector[-1] == "'" and '"' not in selector[1:-1]
):
selector = '"' + selector[1:-1] + '"'
if (
selector.count('"') == 0
and selector.count("'") >= 2
and selector.count("'") % 2 == 0
and "='" in selector
and "']" in selector
):
swap_char = "*_SWAP_CHAR_*"
selector = selector.replace("'", swap_char)
selector = selector.replace('"', "'")
selector = selector.replace(swap_char, '"')
return selector
def wait_for_css_query_selector(
driver, selector, timeout=settings.LARGE_TIMEOUT
):
element = None
selector = escape_quotes_if_needed(selector)
selector = remove_extra_slashes(selector)
selector = optimize_selector(selector)
script = """return document.querySelector('%s');""" % selector
start_ms = time.time() * 1000.0
stop_ms = start_ms + (timeout * 1000.0)
for x in range(int(timeout * 10)):
try:
element = driver.execute_script(script)
if element:
return element
except Exception:
element = None
if not element:
now_ms = time.time() * 1000.0
if now_ms >= stop_ms:
break
time.sleep(0.1)
raise NoSuchElementException(
"Element {%s} was not present after %s seconds!" % (selector, timeout)
)
def is_valid_by(by):
return by in [
"css selector", "class name", "id", "name",
"link text", "xpath", "tag name", "partial link text",
]
def swap_selector_and_by_if_reversed(selector, by):
if not is_valid_by(by) and is_valid_by(selector):
selector, by = by, selector
return (selector, by)
def call_me_later(driver, script, ms):
"""Call script after ms passed."""
call = "function() {%s}" % script
driver.execute_script("window.setTimeout(%s, %s);" % (call, ms))
def highlight(driver, selector, by="css selector", loops=4):
"""For driver.highlight() / driver.page.highlight()"""
swap_selector_and_by_if_reversed(selector, by)
if ":contains(" in selector:
by = "xpath"
selector = css_to_xpath.convert_css_to_xpath(selector)
element = None
try:
element = driver.find_element(by, selector)
except Exception:
time.sleep(1)
element = driver.find_element(by, selector)
o_bs = "" # original_box_shadow
style = element.get_attribute("style")
if style and "box-shadow: " in style:
box_start = style.find("box-shadow: ")
box_end = style.find(";", box_start) + 1
original_box_shadow = style[box_start:box_end]
o_bs = original_box_shadow
highlight_element_with_js(driver, element, loops=loops, o_bs=o_bs)
def highlight_with_js(driver, selector, loops=4, o_bs=""):
try:
# This closes any pop-up alerts
driver.execute_script("")
except Exception:
pass
if selector == "html":
selector = "body"
selector_no_spaces = selector.replace(" ", "")
early_exit = False
if '[style=\\"' in selector_no_spaces:
if "box\\-shadow:" in selector:
early_exit = True # Changing the box-shadow changes the selector
elif '[style=\\"' in selector:
selector = selector.replace('[style=\\"', '[style\\*=\\"')
else:
early_exit = True # Changing the box-shadow changes the selector
if early_exit:
return
script = (
"""document.querySelector('%s').style.boxShadow =
'0px 0px 6px 6px rgba(128, 128, 128, 0.5)';"""
% selector
)
try:
driver.execute_script(script)
except Exception:
return
for n in range(loops):
script = (
"""document.querySelector('%s').style.boxShadow =
'0px 0px 6px 6px rgba(255, 0, 0, 1)';"""
% selector
)
try:
driver.execute_script(script)
except Exception:
return
time.sleep(0.0181)
script = (
"""document.querySelector('%s').style.boxShadow =
'0px 0px 6px 6px rgba(128, 0, 128, 1)';"""
% selector
)
try:
driver.execute_script(script)
except Exception:
return
time.sleep(0.0181)
script = (
"""document.querySelector('%s').style.boxShadow =
'0px 0px 6px 6px rgba(0, 0, 255, 1)';"""
% selector
)
try:
driver.execute_script(script)
except Exception:
return
time.sleep(0.0181)
script = (
"""document.querySelector('%s').style.boxShadow =
'0px 0px 6px 6px rgba(0, 255, 0, 1)';"""
% selector
)
try:
driver.execute_script(script)
except Exception:
return
time.sleep(0.0181)
script = (
"""document.querySelector('%s').style.boxShadow =
'0px 0px 6px 6px rgba(128, 128, 0, 1)';"""
% selector
)
try:
driver.execute_script(script)
except Exception:
return
time.sleep(0.0181)
script = (
"""document.querySelector('%s').style.boxShadow =
'0px 0px 6px 6px rgba(128, 0, 128, 1)';"""
% selector
)
try:
driver.execute_script(script)
except Exception:
return
time.sleep(0.0181)
script = """document.querySelector('%s').style.boxShadow =
'%s';""" % (
selector,
o_bs,
)
try:
driver.execute_script(script)
except Exception:
return
def highlight_element_with_js(driver, element, loops=4, o_bs=""):
try:
# This closes any pop-up alerts
driver.execute_script("")
except Exception:
pass
script = (
"""arguments[0].style.boxShadow =
'0px 0px 6px 6px rgba(128, 128, 128, 0.5)';"""
)
try:
driver.execute_script(script, element)
except Exception:
return
for n in range(loops):
script = (
"""arguments[0].style.boxShadow =
'0px 0px 6px 6px rgba(255, 0, 0, 1)';"""
)
try:
driver.execute_script(script, element)
except Exception:
return
time.sleep(0.0181)
script = (
"""arguments[0].style.boxShadow =
'0px 0px 6px 6px rgba(128, 0, 128, 1)';"""
)
try:
driver.execute_script(script, element)
except Exception:
return
time.sleep(0.0181)
script = (
"""arguments[0].style.boxShadow =
'0px 0px 6px 6px rgba(0, 0, 255, 1)';"""
)
try:
driver.execute_script(script, element)
except Exception:
return
time.sleep(0.0181)
script = (
"""arguments[0].style.boxShadow =
'0px 0px 6px 6px rgba(0, 255, 0, 1)';"""
)
try:
driver.execute_script(script, element)
except Exception:
return
time.sleep(0.0181)
script = (
"""arguments[0].style.boxShadow =
'0px 0px 6px 6px rgba(128, 128, 0, 1)';"""
)
try:
driver.execute_script(script, element)
except Exception:
return
time.sleep(0.0181)
script = (
"""arguments[0].style.boxShadow =
'0px 0px 6px 6px rgba(128, 0, 128, 1)';"""
)
try:
driver.execute_script(script, element)
except Exception:
return
time.sleep(0.0181)
script = """arguments[0].style.boxShadow = '%s';""" % (o_bs)
try:
driver.execute_script(script, element)
except Exception:
return
def highlight_with_jquery(driver, selector, loops=4, o_bs=""):
try:
# This closes any pop-up alerts
driver.execute_script("")
except Exception:
pass
if selector == "html":
selector = "body"
selector_no_spaces = selector.replace(" ", "")
early_exit = False
if '[style=\\"' in selector_no_spaces:
if "box\\-shadow:" in selector:
early_exit = True # Changing the box-shadow changes the selector
elif '[style=\\"' in selector:
selector = selector.replace('[style=\\"', '[style\\*=\\"')
else:
early_exit = True # Changing the box-shadow changes the selector
if early_exit:
return
script = (
"""jQuery('%s').css('box-shadow',
'0px 0px 6px 6px rgba(128, 128, 128, 0.5)');"""
% selector
)
safe_execute_script(driver, script)
for n in range(loops):
script = (
"""jQuery('%s').css('box-shadow',
'0px 0px 6px 6px rgba(255, 0, 0, 1)');"""
% selector
)
driver.execute_script(script)
time.sleep(0.0181)
script = (
"""jQuery('%s').css('box-shadow',
'0px 0px 6px 6px rgba(128, 0, 128, 1)');"""
% selector
)
driver.execute_script(script)
time.sleep(0.0181)
script = (
"""jQuery('%s').css('box-shadow',
'0px 0px 6px 6px rgba(0, 0, 255, 1)');"""
% selector
)
driver.execute_script(script)
time.sleep(0.0181)
script = (
"""jQuery('%s').css('box-shadow',
'0px 0px 6px 6px rgba(0, 255, 0, 1)');"""
% selector
)
driver.execute_script(script)
time.sleep(0.0181)
script = (
"""jQuery('%s').css('box-shadow',
'0px 0px 6px 6px rgba(128, 128, 0, 1)');"""
% selector
)
driver.execute_script(script)
time.sleep(0.0181)
script = (
"""jQuery('%s').css('box-shadow',
'0px 0px 6px 6px rgba(128, 0, 128, 1)');"""
% selector
)
driver.execute_script(script)
time.sleep(0.0181)
script = """jQuery('%s').css('box-shadow', '%s');""" % (selector, o_bs)
driver.execute_script(script)
def add_css_link(driver, css_link):
script_to_add_css = """function injectCSS(css) {
var head_tag=document.getElementsByTagName("head")[0];
var link_tag=document.createElement("link");
link_tag.rel="stylesheet";
link_tag.type="text/css";
link_tag.href=css;
link_tag.crossorigin="anonymous";
head_tag.appendChild(link_tag);
}
injectCSS("%s");"""
css_link = escape_quotes_if_needed(css_link)
driver.execute_script(script_to_add_css % css_link)
def add_js_link(driver, js_link):
script_to_add_js = """function injectJS(link) {
var body_tag=document.getElementsByTagName("body")[0];
var script_tag=document.createElement("script");
script_tag.src=link;
script_tag.type="text/javascript";
script_tag.crossorigin="anonymous";
script_tag.defer;
script_tag.onload=function() { null };
body_tag.appendChild(script_tag);
}
injectJS("%s");"""
js_link = escape_quotes_if_needed(js_link)
driver.execute_script(script_to_add_js % js_link)
def add_css_style(driver, css_style):
add_css_style_script = """function injectStyle(css) {
var head_tag=document.getElementsByTagName("head")[0];
var style_tag=document.createElement("style");
style_tag.type="text/css";
style_tag.appendChild(document.createTextNode(css));
head_tag.appendChild(style_tag);
}
injectStyle("%s");"""
css_style = css_style.replace("\n", "")
css_style = escape_quotes_if_needed(css_style)
driver.execute_script(add_css_style_script % css_style)
def add_js_code_from_link(driver, js_link):
if js_link.startswith("//"):
js_link = "http:" + js_link
js_code = requests.get(js_link, timeout=5).text
add_js_code_script = (
"""var body_tag=document.getElementsByTagName('body').item(0);"""
"""var script_tag=document.createElement("script");"""
"""script_tag.type="text/javascript";"""
"""script_tag.onload=function() { null };"""
"""script_tag.appendChild(document.createTextNode("%s"));"""
"""body_tag.appendChild(script_tag);"""
)
js_code = js_code.replace("\n", " ")
js_code = escape_quotes_if_needed(js_code)
driver.execute_script(add_js_code_script % js_code)
def add_js_code(driver, js_code):
add_js_code_script = (
"""var body_tag=document.getElementsByTagName('body').item(0);"""
"""var script_tag=document.createElement("script");"""
"""script_tag.type="text/javascript";"""
"""script_tag.onload=function() { null };"""
"""script_tag.appendChild(document.createTextNode("%s"));"""
"""body_tag.appendChild(script_tag);"""
)
js_code = js_code.replace("\n", " ")
js_code = escape_quotes_if_needed(js_code)
driver.execute_script(add_js_code_script % js_code)
def add_meta_tag(driver, http_equiv=None, content=None):
if http_equiv is None:
http_equiv = "Content-Security-Policy"
if content is None:
content = (
"default-src *; style-src 'self' 'unsafe-inline'; "
"script-src: 'self' 'unsafe-inline' 'unsafe-eval'"
)
script_to_add_meta = """function injectMeta() {
var meta_tag=document.createElement('meta');
meta_tag.httpEquiv="%s";
meta_tag.content="%s";
document.getElementsByTagName('head')[0].appendChild(meta_tag);
}
injectMeta();""" % (
http_equiv,
content,
)
driver.execute_script(script_to_add_meta)
def is_jquery_confirm_activated(driver):
try:
driver.execute_script("jconfirm;") # Fails if jconfirm is not defined
return True
except Exception:
return False
def activate_jquery_confirm(driver):
jquery_js = constants.JQuery.MIN_JS
jq_confirm_css = constants.JqueryConfirm.MIN_CSS
jq_confirm_js = constants.JqueryConfirm.MIN_JS
if not is_jquery_activated(driver):
add_js_link(driver, jquery_js)
wait_for_jquery_active(driver, timeout=1.2)
add_css_link(driver, jq_confirm_css)
add_js_link(driver, jq_confirm_js)
for x in range(28):
# jQuery-Confirm needs a small amount of time to load & activate.
if x == 14:
add_css_link(driver, jq_confirm_css)
add_js_link(driver, jq_confirm_js)
try:
driver.execute_script("jconfirm;")
wait_for_ready_state_complete(driver)
wait_for_angularjs(driver)
return
except Exception:
time.sleep(0.1)
def activate_html_inspector(driver):
jquery_js = constants.JQuery.MIN_JS
html_inspector_js = constants.HtmlInspector.MIN_JS
if is_html_inspector_activated(driver):
return
if not is_jquery_activated(driver):
add_js_link(driver, jquery_js)
wait_for_jquery_active(driver, timeout=1.2)
wait_for_ready_state_complete(driver)
wait_for_angularjs(driver)
add_js_link(driver, html_inspector_js)
wait_for_ready_state_complete(driver)
wait_for_angularjs(driver)
for x in range(25):
# HTML-Inspector needs a small amount of time to load & activate.
try:
driver.execute_script("HTMLInspector;")
wait_for_ready_state_complete(driver)
wait_for_angularjs(driver)
return
except Exception:
time.sleep(0.1)
wait_for_ready_state_complete(driver)
wait_for_angularjs(driver)
def activate_messenger(driver):
from seleniumbase.core.style_sheet import get_messenger_style
jquery_js = constants.JQuery.MIN_JS
messenger_css = constants.Messenger.MIN_CSS
messenger_js = constants.Messenger.MIN_JS
msgr_theme_flat_js = constants.Messenger.THEME_FLAT_JS
msgr_theme_future_js = constants.Messenger.THEME_FUTURE_JS
msgr_theme_flat_css = constants.Messenger.THEME_FLAT_CSS
msgr_theme_future_css = constants.Messenger.THEME_FUTURE_CSS
msgr_theme_block_css = constants.Messenger.THEME_BLOCK_CSS
msgr_theme_air_css = constants.Messenger.THEME_AIR_CSS
msgr_theme_ice_css = constants.Messenger.THEME_ICE_CSS
spinner_css = constants.Messenger.SPINNER_CSS
underscore_js = constants.Underscore.MIN_JS
msg_style = (
"Messenger.options = {'maxMessages': 8, "
"extraClasses: 'messenger-fixed "
"messenger-on-bottom messenger-on-right', "
"theme: 'future'}"
)
if not is_jquery_activated(driver):
add_js_link(driver, jquery_js)
wait_for_jquery_active(driver, timeout=1.1)
add_css_link(driver, messenger_css)
add_css_link(driver, msgr_theme_flat_css)
add_css_link(driver, msgr_theme_future_css)
add_css_link(driver, msgr_theme_block_css)
add_css_link(driver, msgr_theme_air_css)
add_css_link(driver, msgr_theme_ice_css)
add_js_link(driver, underscore_js)
add_css_link(driver, spinner_css)
add_js_link(driver, messenger_js)
add_css_style(driver, get_messenger_style())
for x in range(10):
# Messenger needs a small amount of time to load & activate.
try:
result = driver.execute_script(
""" if (typeof Messenger === 'undefined') { return "U"; } """
)
if result == "U":
time.sleep(0.022)
continue
else:
break
except Exception:
time.sleep(0.02)
try:
driver.execute_script(msg_style)
add_js_link(driver, msgr_theme_flat_js)
add_js_link(driver, msgr_theme_future_js)
wait_for_ready_state_complete(driver)
wait_for_angularjs(driver)
return
except Exception:
time.sleep(0.1)
def set_messenger_theme(
driver, theme="default", location="default", max_messages="default"
):
if theme == "default":
theme = "future"
if location == "default":
location = "bottom_right"
if hasattr(sb_config, "mobile_emulator") and sb_config.mobile_emulator:
location = "top_center"
if max_messages == "default":
max_messages = "8"
valid_themes = ["flat", "future", "block", "air", "ice"]
if theme not in valid_themes:
raise Exception("Theme: %s is not in %s!" % (theme, valid_themes))
valid_locations = [
"top_left",
"top_center",
"top_right",
"bottom_left",
"bottom_center",
"bottom_right",
]
if location not in valid_locations:
raise Exception(
"Location: %s is not in %s!" % (location, valid_locations)
)
if location == "top_left":
messenger_location = "messenger-on-top messenger-on-left"
elif location == "top_center":
messenger_location = "messenger-on-top"
elif location == "top_right":
messenger_location = "messenger-on-top messenger-on-right"
elif location == "bottom_left":
messenger_location = "messenger-on-bottom messenger-on-left"
elif location == "bottom_center":
messenger_location = "messenger-on-bottom"
elif location == "bottom_right":
messenger_location = "messenger-on-bottom messenger-on-right"
msg_style = (
"Messenger.options = {'maxMessages': %s, "
"extraClasses: 'messenger-fixed %s', theme: '%s'}"
% (max_messages, messenger_location, theme)
)
try:
driver.execute_script(msg_style)
except Exception:
time.sleep(0.03)
activate_messenger(driver)
time.sleep(0.15)
try:
driver.execute_script(msg_style)
time.sleep(0.02)
except Exception:
pass
time.sleep(0.05)
def post_message(driver, message, msg_dur=None, style="info"):
"""A helper method to post a message on the screen with Messenger.
(Should only be called from post_message() in base_case.py)"""
if not msg_dur:
msg_dur = settings.DEFAULT_MESSAGE_DURATION
msg_dur = float(msg_dur)
message = re.escape(message)
message = escape_quotes_if_needed(message)
messenger_script = (
"""Messenger().post({message: "%s", type: "%s", """
"""hideAfter: %s, hideOnNavigate: true});"""
% (message, style, msg_dur)
)
try:
driver.execute_script(messenger_script)
except Exception:
activate_messenger(driver)
set_messenger_theme(driver)
try:
driver.execute_script(messenger_script)
except Exception:
time.sleep(0.17)
activate_messenger(driver)
time.sleep(0.17)
set_messenger_theme(driver)
time.sleep(0.27)
driver.execute_script(messenger_script)
def post_messenger_success_message(driver, message, msg_dur=None):
if not msg_dur:
msg_dur = settings.DEFAULT_MESSAGE_DURATION
msg_dur = float(msg_dur)
try:
theme = "future"
location = "bottom_right"
if hasattr(sb_config, "mobile_emulator") and sb_config.mobile_emulator:
location = "top_right"
set_messenger_theme(driver, theme=theme, location=location)
post_message(driver, message, msg_dur, style="success")
time.sleep(msg_dur + 0.07)
except Exception:
pass
def post_messenger_error_message(driver, message, msg_dur=None):
if not msg_dur:
msg_dur = settings.DEFAULT_MESSAGE_DURATION
msg_dur = float(msg_dur)
try:
set_messenger_theme(driver, theme="block", location="top_center")
post_message(driver, message, msg_dur, style="error")
time.sleep(msg_dur + 0.07)
except Exception:
pass
def highlight_with_js_2(driver, message, selector, o_bs, msg_dur):
try:
# This closes any pop-up alerts
driver.execute_script("")
except Exception:
pass
if selector == "html":
selector = "body"
selector_no_spaces = selector.replace(" ", "")
early_exit = False
if '[style=\\"' in selector_no_spaces:
if "box\\-shadow:" in selector:
early_exit = True # Changing the box-shadow changes the selector
elif '[style=\\"' in selector:
selector = selector.replace('[style=\\"', '[style\\*=\\"')
else:
early_exit = True # Changing the box-shadow changes the selector
if early_exit:
try:
activate_jquery(driver)
post_messenger_success_message(driver, message, msg_dur)
except Exception:
pass
return
script = (
"""document.querySelector('%s').style.boxShadow =
'0px 0px 6px 6px rgba(128, 128, 128, 0.5)';"""
% selector