1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package org.htmlunit.javascript.host.event;
16
17 import java.util.concurrent.atomic.AtomicBoolean;
18
19 import org.htmlunit.WebServerTestCase;
20 import org.htmlunit.html.HtmlPage;
21 import org.htmlunit.junit.annotation.Alerts;
22 import org.junit.jupiter.api.Test;
23
24
25
26
27
28
29
30 public class BeforeUnloadEvent2Test extends WebServerTestCase {
31
32
33
34
35 @Test
36 @Alerts("Second")
37 public void nothing() throws Exception {
38 onbeforeunload("");
39 }
40
41
42
43
44 @Test
45 @Alerts("First")
46 public void setString() throws Exception {
47 onbeforeunload("e.returnValue = 'Hello'");
48 }
49
50
51
52
53 @Test
54 @Alerts("First")
55 public void setNull() throws Exception {
56 onbeforeunload("e.returnValue = null");
57 }
58
59
60
61
62 @Test
63 @Alerts("First")
64 public void returnString() throws Exception {
65 onbeforeunload("return 'Hello'");
66 }
67
68
69
70
71 @Test
72 @Alerts("Second")
73 public void returnNull() throws Exception {
74 onbeforeunload("return null");
75 }
76
77 private void onbeforeunload(final String functionBody) throws Exception {
78 final String html = DOCTYPE_HTML
79 + "<html><head><title>First</title><script>\n"
80 + " window.onbeforeunload = function (e) {\n"
81 + " " + functionBody + ";\n"
82 + " }\n"
83 + "</script></head><body>\n"
84 + " <a href='" + URL_SECOND + "'>Click Here</a>\n"
85 + "</body></html>";
86
87 final String html2 = DOCTYPE_HTML + "<html><head><title>Second</title></head><body></body></html>";
88 getMockWebConnection().setResponse(URL_SECOND, html2);
89
90 final AtomicBoolean called = new AtomicBoolean();
91 getWebClient().setOnbeforeunloadHandler((page, event) -> {
92 called.set(true);
93 return false;
94 });
95 final HtmlPage page = loadPage(html);
96 final HtmlPage page2 = page.getAnchorByText("Click Here").click();
97
98 final boolean expectedFirst = "First".equals(getExpectedAlerts()[0]);
99 if (expectedFirst) {
100 assertSame(page, page2);
101 assertTrue(called.get());
102 }
103 else {
104 assertNotSame(page, page2);
105 assertFalse(called.get());
106 }
107 assertEquals(getExpectedAlerts()[0], page2.getTitleText());
108 }
109
110
111
112
113 @Test
114 @Alerts("First")
115 public void setNullReturnString() throws Exception {
116 onbeforeunload("e.returnValue = null;\n"
117 + "return 'Hello'");
118 }
119
120
121
122
123 @Test
124 @Alerts("First")
125 public void setStringReturnNull() throws Exception {
126 onbeforeunload("e.returnValue = 'Hello';\n"
127 + "return null");
128 }
129
130
131
132
133 @Test
134 @Alerts("First")
135 public void setNullReturnNull() throws Exception {
136 onbeforeunload("e.returnValue = null;\n"
137 + "return null");
138 }
139
140
141
142
143 @Test
144 @Alerts("First")
145 public void setStringReturnString() throws Exception {
146 onbeforeunload("e.returnValue = 'Hello';\n"
147 + "return 'Hello'");
148 }
149 }