-
Notifications
You must be signed in to change notification settings - Fork 6.6k
/
render_frame_host_impl_browsertest.cc
5684 lines (4842 loc) · 237 KB
/
render_frame_host_impl_browsertest.cc
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
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/renderer_host/render_frame_host_impl.h"
#include <memory>
#include <set>
#include <string>
#include <utility>
#include "base/bind.h"
#include "base/callback_helpers.h"
#include "base/files/file_path.h"
#include "base/memory/ptr_util.h"
#include "base/optional.h"
#include "base/path_service.h"
#include "base/run_loop.h"
#include "base/strings/strcat.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/bind.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/mock_callback.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/test_timeouts.h"
#include "build/build_config.h"
#include "components/ukm/test_ukm_recorder.h"
#include "content/browser/browser_main_loop.h"
#include "content/browser/renderer_host/input/timeout_monitor.h"
#include "content/browser/renderer_host/navigation_request.h"
#include "content/browser/renderer_host/render_process_host_impl.h"
#include "content/browser/sms/test/mock_sms_provider.h"
#include "content/browser/web_contents/web_contents_impl.h"
#include "content/common/content_navigation_policy.h"
#include "content/public/browser/javascript_dialog_manager.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_observer.h"
#include "content/public/common/content_client.h"
#include "content/public/common/content_features.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/page_visibility_state.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/content_browser_test.h"
#include "content/public/test/content_browser_test_utils.h"
#include "content/public/test/navigation_handle_observer.h"
#include "content/public/test/render_frame_host_test_support.h"
#include "content/public/test/simple_url_loader_test_helper.h"
#include "content/public/test/test_frame_navigation_observer.h"
#include "content/public/test/test_navigation_observer.h"
#include "content/public/test/test_utils.h"
#include "content/public/test/url_loader_interceptor.h"
#include "content/shell/browser/shell.h"
#include "content/test/content_browser_test_utils_internal.h"
#include "content/test/data/mojo_web_test_helper_test.mojom.h"
#include "content/test/did_commit_navigation_interceptor.h"
#include "content/test/frame_host_test_interface.mojom.h"
#include "content/test/test_content_browser_client.h"
#include "content/test/test_render_frame_host_factory.h"
#include "net/base/features.h"
#include "net/base/ip_address.h"
#include "net/base/ip_endpoint.h"
#include "net/base/net_errors.h"
#include "net/base/schemeful_site.h"
#include "net/cookies/cookie_constants.h"
#include "net/dns/mock_host_resolver.h"
#include "net/test/embedded_test_server/controllable_http_response.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "net/test/embedded_test_server/http_request.h"
#include "net/test/embedded_test_server/request_handler_util.h"
#include "net/traffic_annotation/network_traffic_annotation_test_helper.h"
#include "services/metrics/public/cpp/ukm_source_id.h"
#include "services/network/public/cpp/features.h"
#include "services/network/public/cpp/resource_request.h"
#include "services/network/public/cpp/simple_url_loader.h"
#include "services/network/public/mojom/url_loader_factory.mojom.h"
#include "services/network/test/test_url_loader_factory.h"
#include "services/service_manager/public/cpp/interface_provider.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "third_party/blink/public/mojom/browser_interface_broker.mojom-test-utils.h"
#include "third_party/blink/public/mojom/frame/frame.mojom-test-utils.h"
#include "url/gurl.h"
#include "url/origin.h"
#if defined(OS_ANDROID)
#include "base/android/build_info.h"
#include "third_party/blink/public/mojom/remote_objects/remote_objects.mojom.h"
#endif // defined(OS_ANDROID)
namespace content {
namespace {
// Implementation of ContentBrowserClient that overrides
// OverridePageVisibilityState() and allows consumers to set a value.
class PrerenderTestContentBrowserClient : public TestContentBrowserClient {
public:
PrerenderTestContentBrowserClient()
: override_enabled_(false),
visibility_override_(PageVisibilityState::kVisible) {}
~PrerenderTestContentBrowserClient() override {}
void EnableVisibilityOverride(PageVisibilityState visibility_override) {
override_enabled_ = true;
visibility_override_ = visibility_override;
}
void OverridePageVisibilityState(
RenderFrameHost* render_frame_host,
PageVisibilityState* visibility_state) override {
if (override_enabled_)
*visibility_state = visibility_override_;
}
private:
bool override_enabled_;
PageVisibilityState visibility_override_;
DISALLOW_COPY_AND_ASSIGN(PrerenderTestContentBrowserClient);
};
const char kTrustMeUrl[] = "trustme://host/path/";
const char kTrustMeIfEmbeddingSecureUrl[] =
"trustmeifembeddingsecure://host/path/";
// Configure trustme: as a scheme that should cause cookies to be treated as
// first-party when top-level, and also installs a URLLoaderFactory that
// makes all requests to it via kTrustMeUrl return a particular iframe.
// Same for trustmeifembeddingsecure, which does the same if the embedded origin
// is secure.
class FirstPartySchemeContentBrowserClient : public TestContentBrowserClient {
public:
explicit FirstPartySchemeContentBrowserClient(const GURL& iframe_url)
: iframe_url_(iframe_url) {
trustme_factory_ = std::make_unique<network::TestURLLoaderFactory>();
trustmeifembeddingsecure_factory_ =
std::make_unique<network::TestURLLoaderFactory>();
std::string response_body =
base::StrCat({"<iframe src=\"", iframe_url_.spec(), "\"></iframe>"});
trustme_factory_->AddResponse(kTrustMeUrl, response_body);
trustmeifembeddingsecure_factory_->AddResponse(kTrustMeIfEmbeddingSecureUrl,
response_body);
}
~FirstPartySchemeContentBrowserClient() override = default;
bool ShouldTreatURLSchemeAsFirstPartyWhenTopLevel(
base::StringPiece scheme,
bool is_embedded_origin_secure) override {
if (is_embedded_origin_secure && scheme == "trustmeifembeddingsecure")
return true;
return scheme == "trustme";
}
void RegisterNonNetworkNavigationURLLoaderFactories(
int frame_tree_node_id,
ukm::SourceIdObj ukm_source_id,
NonNetworkURLLoaderFactoryMap* factories) override {
mojo::PendingRemote<network::mojom::URLLoaderFactory> trustme_remote;
trustme_factory_->Clone(trustme_remote.InitWithNewPipeAndPassReceiver());
factories->emplace("trustme", std::move(trustme_remote));
mojo::PendingRemote<network::mojom::URLLoaderFactory>
trustmeifembeddingsecure_remote;
trustmeifembeddingsecure_factory_->Clone(
trustmeifembeddingsecure_remote.InitWithNewPipeAndPassReceiver());
factories->emplace("trustmeifembeddingsecure",
std::move(trustmeifembeddingsecure_remote));
}
private:
GURL iframe_url_;
std::unique_ptr<network::TestURLLoaderFactory> trustme_factory_;
std::unique_ptr<network::TestURLLoaderFactory>
trustmeifembeddingsecure_factory_;
DISALLOW_COPY_AND_ASSIGN(FirstPartySchemeContentBrowserClient);
};
} // anonymous namespace
// TODO(mlamouri): part of these tests were removed because they were dependent
// on an environment were focus is guaranteed. This is only for
// interactive_ui_tests so these bits need to move there.
// See https://crbug.com/491535
class RenderFrameHostImplBrowserTest : public ContentBrowserTest {
public:
using LifecycleStateImpl = RenderFrameHostImpl::LifecycleStateImpl;
RenderFrameHostImplBrowserTest()
: https_server_(net::EmbeddedTestServer::TYPE_HTTPS) {}
~RenderFrameHostImplBrowserTest() override = default;
// Return an URL for loading a local test file.
GURL GetFileURL(const base::FilePath::CharType* file_path) {
base::FilePath path;
CHECK(base::PathService::Get(base::DIR_SOURCE_ROOT, &path));
path = path.Append(GetTestDataFilePath());
path = path.Append(file_path);
return GURL("file:" + path.AsUTF8Unsafe());
}
protected:
void SetUpOnMainThread() override {
host_resolver()->AddRule("*", "127.0.0.1");
SetupCrossSiteRedirector(embedded_test_server());
ASSERT_TRUE(embedded_test_server()->Start());
}
void SetUpCommandLine(base::CommandLine* command_line) override {
// TODO(https://crbug.com/794320): Remove this when the new Java Bridge code
// is integrated into WebView.
base::CommandLine::ForCurrentProcess()->AppendSwitchASCII(
switches::kJavaScriptFlags, "--expose_gc");
base::CommandLine::ForCurrentProcess()->AppendSwitchASCII(
switches::kEnableBlinkFeatures, "WebOTP");
}
net::EmbeddedTestServer* https_server() { return &https_server_; }
WebContentsImpl* web_contents() const {
return static_cast<WebContentsImpl*>(shell()->web_contents());
}
RenderFrameHostImpl* root_frame_host() const {
return web_contents()->GetMainFrame();
}
private:
net::EmbeddedTestServer https_server_;
};
std::string ExecuteJavaScriptMethodAndGetResult(
RenderFrameHostImpl* render_frame,
const std::string& object,
const std::string& method,
base::Value arguments) {
bool executing = true;
std::string result;
base::OnceCallback<void(base::Value)> call_back = base::BindOnce(
[](bool* flag, std::string* reason, base::Value value) {
*flag = false;
DCHECK(value.is_string());
*reason = value.GetString();
},
base::Unretained(&executing), base::Unretained(&result));
render_frame->ExecuteJavaScriptMethod(
base::UTF8ToUTF16(object), base::UTF8ToUTF16(method),
std::move(arguments), std::move(call_back));
while (executing) {
base::RunLoop loop;
loop.RunUntilIdle();
}
return result;
}
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
ExecuteJavaScriptMethodWorksWithArguments) {
EXPECT_TRUE(NavigateToURL(
shell(), GetTestUrl("render_frame_host", "jsMethodTest.html")));
RenderFrameHostImpl* render_frame = web_contents()->GetMainFrame();
render_frame->AllowInjectingJavaScript();
base::Value empty_arguments(base::Value::Type::LIST);
std::string result = ExecuteJavaScriptMethodAndGetResult(
render_frame, "window", "someMethod", std::move(empty_arguments));
EXPECT_EQ(result, "called someMethod()");
base::Value single_arguments(base::Value::Type::LIST);
single_arguments.Append("arg1");
result = ExecuteJavaScriptMethodAndGetResult(
render_frame, "window", "someMethod", std::move(single_arguments));
EXPECT_EQ(result, "called someMethod(arg1)");
base::Value four_arguments(base::Value::Type::LIST);
four_arguments.Append("arg1");
four_arguments.Append("arg2");
four_arguments.Append("arg3");
four_arguments.Append("arg4");
result = ExecuteJavaScriptMethodAndGetResult(
render_frame, "window", "someMethod", std::move(four_arguments));
EXPECT_EQ(result, "called someMethod(arg1,arg2,arg3,arg4)");
}
// Test that when creating a new window, the main frame is correctly focused.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest, IsFocused_AtLoad) {
EXPECT_TRUE(
NavigateToURL(shell(), GetTestUrl("render_frame_host", "focus.html")));
// The main frame should be focused.
EXPECT_EQ(web_contents()->GetMainFrame(), web_contents()->GetFocusedFrame());
}
// Test that if the content changes the focused frame, it is correctly exposed.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest, IsFocused_Change) {
EXPECT_TRUE(
NavigateToURL(shell(), GetTestUrl("render_frame_host", "focus.html")));
std::string frames[2] = {"frame1", "frame2"};
for (const std::string& frame : frames) {
EXPECT_TRUE(ExecJs(web_contents()->GetMainFrame(), "focus" + frame + "()"));
// The main frame is not the focused frame in the frame tree but the main
// frame is focused per RFHI rules because one of its descendant is focused.
// TODO(mlamouri): we should check the frame focus state per RFHI, see the
// general comment at the beginning of this test file.
EXPECT_NE(web_contents()->GetMainFrame(),
web_contents()->GetFocusedFrame());
EXPECT_EQ(frame, web_contents()->GetFocusedFrame()->GetFrameName());
}
}
// Tests focus behavior when the focused frame is removed from the frame tree.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest, RemoveFocusedFrame) {
EXPECT_TRUE(
NavigateToURL(shell(), GetTestUrl("render_frame_host", "focus.html")));
EXPECT_TRUE(ExecJs(web_contents()->GetMainFrame(), "focusframe4()"));
EXPECT_NE(web_contents()->GetMainFrame(), web_contents()->GetFocusedFrame());
EXPECT_EQ("frame4", web_contents()->GetFocusedFrame()->GetFrameName());
EXPECT_EQ("frame3",
web_contents()->GetFocusedFrame()->GetParent()->GetFrameName());
EXPECT_NE(-1, web_contents()->GetFrameTree()->focused_frame_tree_node_id_);
EXPECT_TRUE(ExecJs(web_contents()->GetMainFrame(), "detachframe(3)"));
EXPECT_EQ(nullptr, web_contents()->GetFocusedFrame());
EXPECT_EQ(-1, web_contents()->GetFrameTree()->focused_frame_tree_node_id_);
EXPECT_TRUE(ExecJs(web_contents()->GetMainFrame(), "focusframe2()"));
EXPECT_NE(nullptr, web_contents()->GetFocusedFrame());
EXPECT_NE(web_contents()->GetMainFrame(), web_contents()->GetFocusedFrame());
EXPECT_NE(-1, web_contents()->GetFrameTree()->focused_frame_tree_node_id_);
EXPECT_TRUE(ExecJs(web_contents()->GetMainFrame(), "detachframe(2)"));
EXPECT_EQ(nullptr, web_contents()->GetFocusedFrame());
EXPECT_EQ(-1, web_contents()->GetFrameTree()->focused_frame_tree_node_id_);
}
// Test that a frame is visible/hidden depending on its WebContents visibility
// state.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
GetVisibilityState_Basic) {
EXPECT_TRUE(NavigateToURL(shell(), GURL("data:text/html,foo")));
web_contents()->WasShown();
EXPECT_EQ(PageVisibilityState::kVisible,
web_contents()->GetMainFrame()->GetVisibilityState());
web_contents()->WasHidden();
EXPECT_EQ(PageVisibilityState::kHidden,
web_contents()->GetMainFrame()->GetVisibilityState());
}
// Test that a frame visibility can be overridden by the ContentBrowserClient.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
GetVisibilityState_Override) {
EXPECT_TRUE(NavigateToURL(shell(), GURL("data:text/html,foo")));
PrerenderTestContentBrowserClient new_client;
ContentBrowserClient* old_client = SetBrowserClientForTesting(&new_client);
web_contents()->WasShown();
EXPECT_EQ(PageVisibilityState::kVisible,
web_contents()->GetMainFrame()->GetVisibilityState());
new_client.EnableVisibilityOverride(PageVisibilityState::kHiddenButPainting);
EXPECT_EQ(PageVisibilityState::kHiddenButPainting,
web_contents()->GetMainFrame()->GetVisibilityState());
SetBrowserClientForTesting(old_client);
}
// Check that the URLLoaderFactories created by RenderFrameHosts for renderers
// are not trusted.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
URLLoaderFactoryNotTrusted) {
EXPECT_TRUE(NavigateToURL(shell(), embedded_test_server()->GetURL("/echo")));
mojo::Remote<network::mojom::URLLoaderFactory> url_loader_factory;
web_contents()->GetMainFrame()->CreateNetworkServiceDefaultFactory(
url_loader_factory.BindNewPipeAndPassReceiver());
std::unique_ptr<network::ResourceRequest> request =
std::make_unique<network::ResourceRequest>();
request->url = embedded_test_server()->GetURL("/echo");
request->request_initiator =
url::Origin::Create(embedded_test_server()->base_url());
request->trusted_params = network::ResourceRequest::TrustedParams();
content::SimpleURLLoaderTestHelper simple_loader_helper;
std::unique_ptr<network::SimpleURLLoader> simple_loader =
network::SimpleURLLoader::Create(std::move(request),
TRAFFIC_ANNOTATION_FOR_TESTS);
simple_loader->DownloadToStringOfUnboundedSizeUntilCrashAndDie(
url_loader_factory.get(), simple_loader_helper.GetCallback());
simple_loader_helper.WaitForCallback();
EXPECT_FALSE(simple_loader_helper.response_body());
EXPECT_EQ(net::ERR_INVALID_ARGUMENT, simple_loader->NetError());
}
namespace {
class TestJavaScriptDialogManager : public JavaScriptDialogManager,
public WebContentsDelegate {
public:
TestJavaScriptDialogManager()
: message_loop_runner_(new MessageLoopRunner), url_invalidate_count_(0) {}
~TestJavaScriptDialogManager() override {}
// This waits until either WCD::BeforeUnloadFired is called (the unload has
// been handled) or JSDM::RunJavaScriptDialog/RunBeforeUnloadDialog is called
// (a request to display a dialog has been received).
void Wait() {
message_loop_runner_->Run();
message_loop_runner_ = new MessageLoopRunner;
}
// Runs the dialog callback.
void Run(bool success, const std::u16string& user_input) {
std::move(callback_).Run(success, user_input);
}
int num_beforeunload_dialogs_seen() { return num_beforeunload_dialogs_seen_; }
int num_beforeunload_fired_seen() { return num_beforeunload_fired_seen_; }
bool proceed() { return proceed_; }
// WebContentsDelegate
JavaScriptDialogManager* GetJavaScriptDialogManager(
WebContents* source) override {
return this;
}
void BeforeUnloadFired(WebContents* tab,
bool proceed,
bool* proceed_to_fire_unload) override {
++num_beforeunload_fired_seen_;
proceed_ = proceed;
message_loop_runner_->Quit();
}
// JavaScriptDialogManager
void RunJavaScriptDialog(WebContents* web_contents,
RenderFrameHost* render_frame_host,
JavaScriptDialogType dialog_type,
const std::u16string& message_text,
const std::u16string& default_prompt_text,
DialogClosedCallback callback,
bool* did_suppress_message) override {
callback_ = std::move(callback);
message_loop_runner_->Quit();
}
void RunBeforeUnloadDialog(WebContents* web_contents,
RenderFrameHost* render_frame_host,
bool is_reload,
DialogClosedCallback callback) override {
++num_beforeunload_dialogs_seen_;
callback_ = std::move(callback);
message_loop_runner_->Quit();
}
bool HandleJavaScriptDialog(WebContents* web_contents,
bool accept,
const std::u16string* prompt_override) override {
return true;
}
void CancelDialogs(WebContents* web_contents, bool reset_state) override {}
// Keep track of whether the tab has notified us of a navigation state change
// which invalidates the displayed URL.
void NavigationStateChanged(WebContents* source,
InvalidateTypes changed_flags) override {
if (changed_flags & INVALIDATE_TYPE_URL)
url_invalidate_count_++;
}
int url_invalidate_count() { return url_invalidate_count_; }
void reset_url_invalidate_count() { url_invalidate_count_ = 0; }
private:
DialogClosedCallback callback_;
// The MessageLoopRunner used to spin the message loop.
scoped_refptr<MessageLoopRunner> message_loop_runner_;
// The number of times NavigationStateChanged has been called.
int url_invalidate_count_;
// The total number of beforeunload dialogs seen by this dialog manager.
int num_beforeunload_dialogs_seen_ = 0;
// The total number of BeforeUnloadFired events witnessed by the
// WebContentsDelegate.
int num_beforeunload_fired_seen_ = 0;
// The |proceed| value returned by the last unload event.
bool proceed_ = false;
DISALLOW_COPY_AND_ASSIGN(TestJavaScriptDialogManager);
};
// A RenderFrameHostImpl that discards callback for BeforeUnload.
class RenderFrameHostImplForBeforeUnloadInterceptor
: public RenderFrameHostImpl {
public:
using RenderFrameHostImpl::RenderFrameHostImpl;
void SendBeforeUnload(bool is_reload,
base::WeakPtr<RenderFrameHostImpl> rfh) override {
rfh->GetAssociatedLocalFrame()->BeforeUnload(is_reload, base::DoNothing());
}
private:
friend class RenderFrameHostFactoryForBeforeUnloadInterceptor;
};
class RenderFrameHostFactoryForBeforeUnloadInterceptor
: public TestRenderFrameHostFactory {
protected:
std::unique_ptr<RenderFrameHostImpl> CreateRenderFrameHost(
SiteInstance* site_instance,
scoped_refptr<RenderViewHostImpl> render_view_host,
RenderFrameHostDelegate* delegate,
FrameTree* frame_tree,
FrameTreeNode* frame_tree_node,
int32_t routing_id,
mojo::PendingAssociatedRemote<mojom::Frame> frame_remote,
const blink::LocalFrameToken& frame_token,
bool renderer_initiated_creation,
RenderFrameHostImpl::LifecycleStateImpl lifecycle_state) override {
return base::WrapUnique(new RenderFrameHostImplForBeforeUnloadInterceptor(
site_instance, std::move(render_view_host), delegate, frame_tree,
frame_tree_node, routing_id, std::move(frame_remote), frame_token,
renderer_initiated_creation, lifecycle_state));
}
};
mojo::ScopedMessagePipeHandle CreateDisconnectedMessagePipeHandle() {
mojo::MessagePipe pipe;
return std::move(pipe.handle0);
}
} // namespace
// Tests that a beforeunload dialog in an iframe doesn't stop the beforeunload
// timer of a parent frame.
// TODO(avi): flaky on Linux TSAN: http://crbug.com/795326
#if (defined(OS_LINUX) || defined(OS_CHROMEOS)) && defined(THREAD_SANITIZER)
#define MAYBE_IframeBeforeUnloadParentHang DISABLED_IframeBeforeUnloadParentHang
#else
#define MAYBE_IframeBeforeUnloadParentHang IframeBeforeUnloadParentHang
#endif
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
MAYBE_IframeBeforeUnloadParentHang) {
RenderFrameHostFactoryForBeforeUnloadInterceptor interceptor;
TestJavaScriptDialogManager dialog_manager;
web_contents()->SetDelegate(&dialog_manager);
EXPECT_TRUE(NavigateToURL(shell(), GURL("about:blank")));
// Make an iframe with a beforeunload handler.
std::string script =
"var iframe = document.createElement('iframe');"
"document.body.appendChild(iframe);"
"iframe.contentWindow.onbeforeunload=function(e){return 'x'};";
EXPECT_TRUE(ExecJs(web_contents(), script));
EXPECT_TRUE(WaitForLoadStop(web_contents()));
// JavaScript onbeforeunload dialogs require a user gesture.
for (auto* frame : web_contents()->GetAllFrames())
frame->ExecuteJavaScriptWithUserGestureForTests(std::u16string());
// Force a process switch by going to a privileged page. The beforeunload
// timer will be started on the top-level frame but will be paused while the
// beforeunload dialog is shown by the subframe.
GURL web_ui_page(std::string(kChromeUIScheme) + "://" +
std::string(kChromeUIGpuHost));
shell()->LoadURL(web_ui_page);
dialog_manager.Wait();
RenderFrameHostImpl* main_frame = web_contents()->GetMainFrame();
EXPECT_TRUE(main_frame->is_waiting_for_beforeunload_completion());
// Answer the dialog.
dialog_manager.Run(true, std::u16string());
// There will be no beforeunload completion callback invocation, so if the
// beforeunload completion callback timer isn't functioning then the
// navigation will hang forever and this test will time out. If this waiting
// for the load stop works, this test won't time out.
EXPECT_TRUE(WaitForLoadStop(web_contents()));
EXPECT_EQ(web_ui_page, web_contents()->GetLastCommittedURL());
web_contents()->SetDelegate(nullptr);
web_contents()->SetJavaScriptDialogManagerForTesting(nullptr);
}
// Tests that a gesture is required in a frame before it can request a
// beforeunload dialog.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
BeforeUnloadDialogRequiresGesture) {
TestJavaScriptDialogManager dialog_manager;
web_contents()->SetDelegate(&dialog_manager);
EXPECT_TRUE(NavigateToURL(
shell(), GetTestUrl("render_frame_host", "beforeunload.html")));
// Disable the hang monitor, otherwise there will be a race between the
// beforeunload dialog and the beforeunload hang timer.
web_contents()->GetMainFrame()->DisableBeforeUnloadHangMonitorForTesting();
// Reload. There should be no beforeunload dialog because there was no gesture
// on the page. If there was, this WaitForLoadStop call will hang.
web_contents()->GetController().Reload(ReloadType::NORMAL, false);
EXPECT_TRUE(WaitForLoadStop(web_contents()));
// Give the page a user gesture and try reloading again. This time there
// should be a dialog. If there is no dialog, the call to Wait will hang.
web_contents()->GetMainFrame()->ExecuteJavaScriptWithUserGestureForTests(
std::u16string());
web_contents()->GetController().Reload(ReloadType::NORMAL, false);
dialog_manager.Wait();
// Answer the dialog.
dialog_manager.Run(true, std::u16string());
EXPECT_TRUE(WaitForLoadStop(web_contents()));
// The reload should have cleared the user gesture bit, so upon leaving again
// there should be no beforeunload dialog.
shell()->LoadURL(GURL("about:blank"));
EXPECT_TRUE(WaitForLoadStop(web_contents()));
web_contents()->SetDelegate(nullptr);
web_contents()->SetJavaScriptDialogManagerForTesting(nullptr);
}
// Test for crbug.com/80401. Canceling a beforeunload dialog should reset
// the URL to the previous page's URL.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
CancelBeforeUnloadResetsURL) {
TestJavaScriptDialogManager dialog_manager;
web_contents()->SetDelegate(&dialog_manager);
GURL url(GetTestUrl("render_frame_host", "beforeunload.html"));
EXPECT_TRUE(NavigateToURL(shell(), url));
PrepContentsForBeforeUnloadTest(web_contents());
// Navigate to a page that triggers a cross-site transition.
GURL url2(embedded_test_server()->GetURL("foo.com", "/title1.html"));
shell()->LoadURL(url2);
dialog_manager.Wait();
// Cancel the dialog.
dialog_manager.reset_url_invalidate_count();
dialog_manager.Run(false, std::u16string());
EXPECT_FALSE(web_contents()->IsLoading());
// Verify there are no pending history items after the dialog is cancelled.
// (see crbug.com/93858)
NavigationEntry* entry = web_contents()->GetController().GetPendingEntry();
EXPECT_EQ(nullptr, entry);
EXPECT_EQ(url, web_contents()->GetVisibleURL());
// There should have been at least one NavigationStateChange event for
// invalidating the URL in the address bar, to avoid leaving the stale URL
// visible.
EXPECT_GE(dialog_manager.url_invalidate_count(), 1);
web_contents()->SetDelegate(nullptr);
web_contents()->SetJavaScriptDialogManagerForTesting(nullptr);
}
// Helper class for beforunload tests. Sets up a custom dialog manager for the
// main WebContents and provides helpers to register and test beforeunload
// handlers.
//
// TODO(alexmos): Refactor other beforeunload tests in this file to use this
// class.
class RenderFrameHostImplBeforeUnloadBrowserTest
: public RenderFrameHostImplBrowserTest {
public:
RenderFrameHostImplBeforeUnloadBrowserTest() {}
TestJavaScriptDialogManager* dialog_manager() {
return dialog_manager_.get();
}
void CloseDialogAndProceed() {
dialog_manager_->Run(true /* navigation should proceed */,
std::u16string());
}
void CloseDialogAndCancel() {
dialog_manager_->Run(false /* navigation should proceed */,
std::u16string());
}
// Installs a beforeunload handler in the given frame.
// |before_unload_options| specify whether the handler should send a "ping"
// message through domAutomationController, and/or whether it should trigger
// the modal beforeunload confirmation dialog.
enum BeforeUnloadOptions {
SHOW_DIALOG = 1,
SEND_PING = 2,
};
void InstallBeforeUnloadHandler(FrameTreeNode* ftn,
int before_unload_options) {
std::string script = "window.onbeforeunload = () => { ";
if (before_unload_options & SEND_PING)
script += "domAutomationController.send('ping'); ";
if (before_unload_options & SHOW_DIALOG)
script += "return 'x'; ";
script += " }";
EXPECT_TRUE(ExecJs(ftn, script));
}
int RetrievePingsFromMessageQueue(DOMMessageQueue* msg_queue) {
int num_pings = 0;
std::string message;
while (msg_queue->PopMessage(&message)) {
base::TrimString(message, "\"", &message);
// Only count messages from beforeunload. For example, an ExecuteScript
// sends its own message to DOMMessageQueue, which we need to ignore.
if (message == "ping")
++num_pings;
}
return num_pings;
}
protected:
void SetUpOnMainThread() override {
RenderFrameHostImplBrowserTest::SetUpOnMainThread();
dialog_manager_ = std::make_unique<TestJavaScriptDialogManager>();
web_contents()->SetDelegate(dialog_manager_.get());
}
void TearDownOnMainThread() override {
web_contents()->SetDelegate(nullptr);
web_contents()->SetJavaScriptDialogManagerForTesting(nullptr);
RenderFrameHostImplBrowserTest::TearDownOnMainThread();
}
private:
std::unique_ptr<TestJavaScriptDialogManager> dialog_manager_;
DISALLOW_COPY_AND_ASSIGN(RenderFrameHostImplBeforeUnloadBrowserTest);
};
// Check that when a frame performs a browser-initiated navigation, its
// cross-site subframe is able to execute a beforeunload handler and put up a
// dialog to cancel or allow the navigation. This matters especially in
// --site-per-process mode; see https://crbug.com/853021.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBeforeUnloadBrowserTest,
SubframeShowsDialogWhenMainFrameNavigates) {
GURL main_url(embedded_test_server()->GetURL(
"a.com", "/cross_site_iframe_factory.html?a(b)"));
EXPECT_TRUE(NavigateToURL(shell(), main_url));
// Install a beforeunload handler in the b.com subframe.
FrameTreeNode* root = web_contents()->GetFrameTree()->root();
InstallBeforeUnloadHandler(root->child_at(0), SHOW_DIALOG);
// Disable beforeunload timer to prevent flakiness.
PrepContentsForBeforeUnloadTest(web_contents());
// Navigate cross-site.
GURL cross_site_url(embedded_test_server()->GetURL("c.com", "/title1.html"));
shell()->LoadURL(cross_site_url);
// Only the main frame should be marked as waiting for beforeunload completion
// callback as the frame being navigated.
RenderFrameHostImpl* main_frame = web_contents()->GetMainFrame();
RenderFrameHostImpl* child = root->child_at(0)->current_frame_host();
EXPECT_TRUE(main_frame->is_waiting_for_beforeunload_completion());
EXPECT_FALSE(child->is_waiting_for_beforeunload_completion());
// Sanity check that the main frame is waiting for subframe's beforeunload
// ACK.
EXPECT_EQ(main_frame, child->GetBeforeUnloadInitiator());
EXPECT_EQ(main_frame, main_frame->GetBeforeUnloadInitiator());
// When in a strict SiteInstances mode, LoadURL() should trigger two
// beforeunload IPCs for subframe and the main frame: the subframe has a
// beforeunload handler, and while the main frame does not, we always send the
// IPC to navigating frames, regardless of whether or not they have a handler.
//
// Without strict SiteInstances, only one beforeunload IPC should be sent to
// the main frame, which will handle both (same-process) frames.
EXPECT_EQ(AreStrictSiteInstancesEnabled() ? 2u : 1u,
main_frame->beforeunload_pending_replies_.size());
// Wait for the beforeunload dialog to be shown from the subframe.
dialog_manager()->Wait();
// The main frame should still be waiting for subframe's beforeunload
// completion callback.
EXPECT_EQ(main_frame, child->GetBeforeUnloadInitiator());
EXPECT_EQ(main_frame, main_frame->GetBeforeUnloadInitiator());
EXPECT_TRUE(main_frame->is_waiting_for_beforeunload_completion());
EXPECT_FALSE(child->is_waiting_for_beforeunload_completion());
// In a strict SiteInstances mode, the beforeunload completion callback should
// happen on the child RFH. Without strict SiteInstances, it will come from
// the main frame RFH, which processes beforeunload for both main frame and
// child frame, since they are in the same process and SiteInstance.
RenderFrameHostImpl* frame_that_sent_beforeunload_ipc =
AreStrictSiteInstancesEnabled() ? child : main_frame;
EXPECT_TRUE(main_frame->beforeunload_pending_replies_.count(
frame_that_sent_beforeunload_ipc));
// Answer the dialog with "cancel" to stay on current page.
CloseDialogAndCancel();
EXPECT_TRUE(WaitForLoadStop(web_contents()));
EXPECT_EQ(main_url, web_contents()->GetLastCommittedURL());
// Verify beforeunload state has been cleared.
EXPECT_FALSE(main_frame->is_waiting_for_beforeunload_completion());
EXPECT_FALSE(child->is_waiting_for_beforeunload_completion());
EXPECT_EQ(nullptr, main_frame->GetBeforeUnloadInitiator());
EXPECT_EQ(nullptr, child->GetBeforeUnloadInitiator());
EXPECT_EQ(0u, main_frame->beforeunload_pending_replies_.size());
// Try navigating again. The dialog should come up again.
shell()->LoadURL(cross_site_url);
dialog_manager()->Wait();
EXPECT_TRUE(main_frame->is_waiting_for_beforeunload_completion());
// Now answer the dialog and allow the navigation to proceed. Disable
// unload ACK on the old frame so that it sticks around in pending delete
// state, since the test later verifies that it has received the beforeunload
// ACK.
TestFrameNavigationObserver commit_observer(root);
main_frame->DisableUnloadTimerForTesting();
CloseDialogAndProceed();
commit_observer.WaitForCommit();
EXPECT_EQ(cross_site_url, web_contents()->GetLastCommittedURL());
EXPECT_FALSE(
web_contents()->GetMainFrame()->is_waiting_for_beforeunload_completion());
// The navigation that succeeded was a browser-initiated, main frame
// navigation, so it swapped RenderFrameHosts. |main_frame| should either be
// in pending deletion and waiting for unload ACK or enter back-forward cache,
// but it should not be waiting for the beforeunload completion callback.
EXPECT_THAT(
main_frame->lifecycle_state(),
testing::AnyOf(testing::Eq(LifecycleStateImpl::kRunningUnloadHandlers),
testing::Eq(LifecycleStateImpl::kInBackForwardCache)));
EXPECT_FALSE(main_frame->is_waiting_for_beforeunload_completion());
EXPECT_EQ(0u, main_frame->beforeunload_pending_replies_.size());
EXPECT_EQ(nullptr, main_frame->GetBeforeUnloadInitiator());
}
// Check that when a frame with multiple cross-site subframes navigates, all
// the subframes execute their beforeunload handlers, but at most one
// beforeunload dialog is allowed per navigation.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBeforeUnloadBrowserTest,
MultipleSubframes) {
GURL main_url(embedded_test_server()->GetURL(
"a.com", "/cross_site_iframe_factory.html?a(b(c),b,c(d),c,d)"));
EXPECT_TRUE(NavigateToURL(shell(), main_url));
// Install a beforeunload handler in five of eight frames to send a ping via
// domAutomationController and request a beforeunload dialog.
FrameTreeNode* root = web_contents()->GetFrameTree()->root();
InstallBeforeUnloadHandler(root, SEND_PING | SHOW_DIALOG);
InstallBeforeUnloadHandler(root->child_at(0)->child_at(0),
SEND_PING | SHOW_DIALOG);
InstallBeforeUnloadHandler(root->child_at(1), SEND_PING | SHOW_DIALOG);
InstallBeforeUnloadHandler(root->child_at(2), SEND_PING | SHOW_DIALOG);
InstallBeforeUnloadHandler(root->child_at(2)->child_at(0),
SEND_PING | SHOW_DIALOG);
// Disable beforeunload timer to prevent flakiness.
PrepContentsForBeforeUnloadTest(web_contents());
// Navigate main frame cross-site and wait for the beforeunload dialog to be
// shown from one of the frames.
DOMMessageQueue msg_queue;
GURL cross_site_url(embedded_test_server()->GetURL("e.com", "/title1.html"));
shell()->LoadURL(cross_site_url);
dialog_manager()->Wait();
// Answer the dialog and allow the navigation to proceed.
CloseDialogAndProceed();
EXPECT_TRUE(WaitForLoadStop(web_contents()));
EXPECT_EQ(cross_site_url, web_contents()->GetLastCommittedURL());
// We should've received five beforeunload pings.
EXPECT_EQ(5, RetrievePingsFromMessageQueue(&msg_queue));
// No more beforeunload dialogs shouldn't been shown, due to a policy of at
// most one dialog per navigation.
EXPECT_EQ(1, dialog_manager()->num_beforeunload_dialogs_seen());
}
// Similar to the test above, but test scenarios where the subframes with
// beforeunload handlers aren't local roots.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBeforeUnloadBrowserTest,
NonLocalRootSubframes) {
GURL main_url(embedded_test_server()->GetURL(
"a.com", "/cross_site_iframe_factory.html?a(a(b),c(c))"));
EXPECT_TRUE(NavigateToURL(shell(), main_url));
// Install a beforeunload handler in two of five frames to send a ping via
// domAutomationController and request a beforeunload dialog.
FrameTreeNode* root = web_contents()->GetFrameTree()->root();
InstallBeforeUnloadHandler(root->child_at(0), SEND_PING | SHOW_DIALOG);
InstallBeforeUnloadHandler(root->child_at(0)->child_at(0),
SEND_PING | SHOW_DIALOG);
// Disable beforeunload timer to prevent flakiness.
PrepContentsForBeforeUnloadTest(web_contents());
// Navigate and wait for the beforeunload dialog to be shown from one of the
// frames.
DOMMessageQueue msg_queue;
GURL cross_site_url(embedded_test_server()->GetURL("a.com", "/title1.html"));
shell()->LoadURL(cross_site_url);
dialog_manager()->Wait();
// Answer the dialog and allow the navigation to proceed.
CloseDialogAndProceed();
EXPECT_TRUE(WaitForLoadStop(web_contents()));
EXPECT_EQ(cross_site_url, web_contents()->GetLastCommittedURL());
// We should've received two beforeunload pings.
EXPECT_EQ(2, RetrievePingsFromMessageQueue(&msg_queue));
// No more beforeunload dialogs shouldn't been shown, due to a policy of at
// most one dialog per navigation.
EXPECT_EQ(1, dialog_manager()->num_beforeunload_dialogs_seen());
}
// Test that cross-site subframes run the beforeunload handler when the main
// frame performs a renderer-initiated navigation.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBeforeUnloadBrowserTest,
RendererInitiatedNavigation) {
GURL main_url(embedded_test_server()->GetURL(
"a.com", "/cross_site_iframe_factory.html?a(a,b,c)"));
EXPECT_TRUE(NavigateToURL(shell(), main_url));
// Install a beforeunload handler in both a.com frames to send a ping via
// domAutomationController.
FrameTreeNode* root = web_contents()->GetFrameTree()->root();
InstallBeforeUnloadHandler(root, SEND_PING);
InstallBeforeUnloadHandler(root->child_at(0), SEND_PING);
// Install a beforeunload handler in the b.com frame to put up a dialog.
InstallBeforeUnloadHandler(root->child_at(1), SHOW_DIALOG);
// Disable beforeunload timer to prevent flakiness.
PrepContentsForBeforeUnloadTest(web_contents());
// Start a same-site renderer-initiated navigation. The beforeunload dialog
// from the b.com frame should be shown. The other two a.com frames should
// send pings from their beforeunload handlers.
DOMMessageQueue msg_queue;
GURL new_url(embedded_test_server()->GetURL("a.com", "/title1.html"));
TestNavigationManager navigation_manager(web_contents(), new_url);
// Use ExecuteScriptAsync because a ping may arrive before the script
// execution completion notification and confuse our expectations.
ExecuteScriptAsync(root, "location.href = '" + new_url.spec() + "';");
dialog_manager()->Wait();
// Answer the dialog and allow the navigation to proceed. Note that at this
// point, without site isolation, the navigation hasn't started yet, as the
// navigating frame is still processing beforeunload for all its descendant
// local frames. With site isolation, the a.com frames have finished
// beforeunload, and the browser process has received OnBeginNavigation, but
// the navigation is paused until the b.com subframe process finishes running
// beforeunload.
CloseDialogAndProceed();
// Wait for navigation to end.
navigation_manager.WaitForNavigationFinished();
EXPECT_EQ(new_url, web_contents()->GetLastCommittedURL());
// We should have received two pings from two a.com frames. If we receive
// more, that probably means we ran beforeunload an extra time in the a.com
// frames.
EXPECT_EQ(2, RetrievePingsFromMessageQueue(&msg_queue));
EXPECT_EQ(1, dialog_manager()->num_beforeunload_dialogs_seen());
}
// Similar to the test above, but check a navigation in a subframe rather than
// the main frame.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBeforeUnloadBrowserTest,
RendererInitiatedNavigationInSubframe) {
GURL main_url(embedded_test_server()->GetURL(
"a.com", "/cross_site_iframe_factory.html?a(b(c),c)"));
EXPECT_TRUE(NavigateToURL(shell(), main_url));
// Install a beforeunload handler to send a ping in all frames.