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