Re-enable WebViewTest.TestConfirmDialog on Mac
[chromium-blink-merge.git] / chrome / browser / apps / guest_view / web_view_browsertest.cc
blob6fd2c1b6fab9d3d1d718d6fea3409033a2e5321d
1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include <queue>
7 #include "base/location.h"
8 #include "base/path_service.h"
9 #include "base/process/process.h"
10 #include "base/single_thread_task_runner.h"
11 #include "base/strings/stringprintf.h"
12 #include "base/strings/utf_string_conversions.h"
13 #include "base/thread_task_runner_handle.h"
14 #include "chrome/app/chrome_command_ids.h"
15 #include "chrome/browser/apps/app_browsertest_util.h"
16 #include "chrome/browser/chrome_content_browser_client.h"
17 #include "chrome/browser/content_settings/host_content_settings_map_factory.h"
18 #include "chrome/browser/lifetime/application_lifetime.h"
19 #include "chrome/browser/pdf/pdf_extension_test_util.h"
20 #include "chrome/browser/prerender/prerender_link_manager.h"
21 #include "chrome/browser/prerender/prerender_link_manager_factory.h"
22 #include "chrome/browser/profiles/profile.h"
23 #include "chrome/browser/renderer_context_menu/render_view_context_menu.h"
24 #include "chrome/browser/renderer_context_menu/render_view_context_menu_test_util.h"
25 #include "chrome/browser/task_management/task_management_browsertest_util.h"
26 #include "chrome/browser/task_manager/task_manager_browsertest_util.h"
27 #include "chrome/browser/ui/browser.h"
28 #include "chrome/browser/ui/browser_dialogs.h"
29 #include "chrome/browser/ui/tabs/tab_strip_model.h"
30 #include "chrome/test/base/ui_test_utils.h"
31 #include "components/content_settings/core/browser/host_content_settings_map.h"
32 #include "components/guest_view/browser/guest_view_manager.h"
33 #include "components/guest_view/browser/guest_view_manager_delegate.h"
34 #include "components/guest_view/browser/guest_view_manager_factory.h"
35 #include "components/guest_view/browser/test_guest_view_manager.h"
36 #include "content/public/browser/gpu_data_manager.h"
37 #include "content/public/browser/interstitial_page.h"
38 #include "content/public/browser/interstitial_page_delegate.h"
39 #include "content/public/browser/notification_service.h"
40 #include "content/public/browser/render_process_host.h"
41 #include "content/public/browser/web_contents_delegate.h"
42 #include "content/public/common/child_process_host.h"
43 #include "content/public/common/content_switches.h"
44 #include "content/public/test/browser_test_utils.h"
45 #include "content/public/test/fake_speech_recognition_manager.h"
46 #include "content/public/test/test_renderer_host.h"
47 #include "extensions/browser/api/declarative/rules_registry.h"
48 #include "extensions/browser/api/declarative/rules_registry_service.h"
49 #include "extensions/browser/api/declarative/test_rules_registry.h"
50 #include "extensions/browser/api/declarative_webrequest/webrequest_constants.h"
51 #include "extensions/browser/api/extensions_api_client.h"
52 #include "extensions/browser/app_window/native_app_window.h"
53 #include "extensions/browser/guest_view/web_view/web_view_guest.h"
54 #include "extensions/common/extension.h"
55 #include "extensions/common/extensions_client.h"
56 #include "extensions/test/extension_test_message_listener.h"
57 #include "media/base/media_switches.h"
58 #include "net/test/embedded_test_server/embedded_test_server.h"
59 #include "net/test/embedded_test_server/http_request.h"
60 #include "net/test/embedded_test_server/http_response.h"
61 #include "ui/aura/window.h"
62 #include "ui/base/l10n/l10n_util.h"
63 #include "ui/compositor/compositor.h"
64 #include "ui/compositor/compositor_observer.h"
65 #include "ui/events/event_switches.h"
66 #include "ui/gfx/switches.h"
67 #include "ui/gl/gl_switches.h"
68 #include "ui/views/view.h"
69 #include "ui/views/widget/widget.h"
71 #if defined(ENABLE_PLUGINS)
72 #include "content/public/browser/plugin_service.h"
73 #include "content/public/common/webplugininfo.h"
74 #include "content/public/test/ppapi_test_utils.h"
75 #endif
77 #if defined(OS_CHROMEOS)
78 #include "chrome/browser/chromeos/accessibility/accessibility_manager.h"
79 #include "chrome/browser/chromeos/accessibility/speech_monitor.h"
80 #endif
82 // For fine-grained suppression on flaky tests.
83 #if defined(OS_WIN)
84 #include "base/win/windows_version.h"
85 #endif
87 using extensions::ContextMenuMatcher;
88 using extensions::ExtensionsAPIClient;
89 using extensions::MenuItem;
90 using guest_view::GuestViewManager;
91 using guest_view::TestGuestViewManager;
92 using guest_view::TestGuestViewManagerFactory;
93 using prerender::PrerenderLinkManager;
94 using prerender::PrerenderLinkManagerFactory;
95 using task_manager::browsertest_util::MatchAboutBlankTab;
96 using task_manager::browsertest_util::MatchAnyApp;
97 using task_manager::browsertest_util::MatchAnyBackground;
98 using task_manager::browsertest_util::MatchAnyTab;
99 using task_manager::browsertest_util::MatchAnyWebView;
100 using task_manager::browsertest_util::MatchApp;
101 using task_manager::browsertest_util::MatchBackground;
102 using task_manager::browsertest_util::MatchWebView;
103 using task_manager::browsertest_util::WaitForTaskManagerRows;
104 using ui::MenuModel;
106 namespace {
107 const char kEmptyResponsePath[] = "/close-socket";
108 const char kRedirectResponsePath[] = "/server-redirect";
109 const char kUserAgentRedirectResponsePath[] = "/detect-user-agent";
110 const char kCacheResponsePath[] = "/cache-control-response";
111 const char kRedirectResponseFullPath[] =
112 "/extensions/platform_apps/web_view/shim/guest_redirect.html";
114 class EmptyHttpResponse : public net::test_server::HttpResponse {
115 public:
116 std::string ToResponseString() const override { return std::string(); }
119 class TestInterstitialPageDelegate : public content::InterstitialPageDelegate {
120 public:
121 TestInterstitialPageDelegate() {
123 ~TestInterstitialPageDelegate() override {}
124 std::string GetHTMLContents() override { return std::string(); }
127 class WebContentsHiddenObserver : public content::WebContentsObserver {
128 public:
129 WebContentsHiddenObserver(content::WebContents* web_contents,
130 const base::Closure& hidden_callback)
131 : WebContentsObserver(web_contents),
132 hidden_callback_(hidden_callback),
133 hidden_observed_(false) {
136 // WebContentsObserver.
137 void WasHidden() override {
138 hidden_observed_ = true;
139 hidden_callback_.Run();
142 bool hidden_observed() { return hidden_observed_; }
144 private:
145 base::Closure hidden_callback_;
146 bool hidden_observed_;
148 DISALLOW_COPY_AND_ASSIGN(WebContentsHiddenObserver);
151 // Watches for context menu to be shown, records count of how many times
152 // context menu was shown.
153 class ContextMenuCallCountObserver {
154 public:
155 ContextMenuCallCountObserver()
156 : num_times_shown_(0),
157 menu_observer_(chrome::NOTIFICATION_RENDER_VIEW_CONTEXT_MENU_SHOWN,
158 base::Bind(&ContextMenuCallCountObserver::OnMenuShown,
159 base::Unretained(this))) {
161 ~ContextMenuCallCountObserver() {}
163 bool OnMenuShown(const content::NotificationSource& source,
164 const content::NotificationDetails& details) {
165 ++num_times_shown_;
166 auto context_menu = content::Source<RenderViewContextMenu>(source).ptr();
167 base::ThreadTaskRunnerHandle::Get()->PostTask(
168 FROM_HERE, base::Bind(&RenderViewContextMenuBase::Cancel,
169 base::Unretained(context_menu)));
170 return true;
173 void Wait() { menu_observer_.Wait(); }
175 int num_times_shown() { return num_times_shown_; }
177 private:
178 int num_times_shown_;
179 content::WindowedNotificationObserver menu_observer_;
181 DISALLOW_COPY_AND_ASSIGN(ContextMenuCallCountObserver);
184 class EmbedderWebContentsObserver : public content::WebContentsObserver {
185 public:
186 explicit EmbedderWebContentsObserver(content::WebContents* web_contents)
187 : WebContentsObserver(web_contents), terminated_(false) {}
189 // WebContentsObserver.
190 void RenderProcessGone(base::TerminationStatus status) override {
191 terminated_ = true;
192 if (message_loop_runner_.get())
193 message_loop_runner_->Quit();
196 void WaitForEmbedderRenderProcessTerminate() {
197 if (terminated_)
198 return;
199 message_loop_runner_ = new content::MessageLoopRunner;
200 message_loop_runner_->Run();
203 private:
204 bool terminated_;
205 scoped_refptr<content::MessageLoopRunner> message_loop_runner_;
207 DISALLOW_COPY_AND_ASSIGN(EmbedderWebContentsObserver);
210 void ExecuteScriptWaitForTitle(content::WebContents* web_contents,
211 const char* script,
212 const char* title) {
213 base::string16 expected_title(base::ASCIIToUTF16(title));
214 base::string16 error_title(base::ASCIIToUTF16("error"));
216 content::TitleWatcher title_watcher(web_contents, expected_title);
217 title_watcher.AlsoWaitForTitle(error_title);
218 EXPECT_TRUE(content::ExecuteScript(web_contents, script));
219 EXPECT_EQ(expected_title, title_watcher.WaitAndGetTitle());
222 #if defined (USE_AURA)
223 views::View* FindWebView(views::View* view) {
224 std::queue<views::View*> queue;
225 queue.push(view);
226 while (!queue.empty()) {
227 views::View* current = queue.front();
228 queue.pop();
229 if (std::string(current->GetClassName()).find("WebView") !=
230 std::string::npos) {
231 return current;
234 for (int i = 0; i < current->child_count(); ++i)
235 queue.push(current->child_at(i));
237 return nullptr;
239 #endif
241 } // namespace
243 // This class intercepts media access request from the embedder. The request
244 // should be triggered only if the embedder API (from tests) allows the request
245 // in Javascript.
246 // We do not issue the actual media request; the fact that the request reached
247 // embedder's WebContents is good enough for our tests. This is also to make
248 // the test run successfully on trybots.
249 class MockWebContentsDelegate : public content::WebContentsDelegate {
250 public:
251 MockWebContentsDelegate()
252 : requested_(false),
253 checked_(false) {}
254 ~MockWebContentsDelegate() override {}
256 void RequestMediaAccessPermission(
257 content::WebContents* web_contents,
258 const content::MediaStreamRequest& request,
259 const content::MediaResponseCallback& callback) override {
260 requested_ = true;
261 if (request_message_loop_runner_.get())
262 request_message_loop_runner_->Quit();
265 bool CheckMediaAccessPermission(content::WebContents* web_contents,
266 const GURL& security_origin,
267 content::MediaStreamType type) override {
268 checked_ = true;
269 if (check_message_loop_runner_.get())
270 check_message_loop_runner_->Quit();
271 return true;
274 void WaitForRequestMediaPermission() {
275 if (requested_)
276 return;
277 request_message_loop_runner_ = new content::MessageLoopRunner;
278 request_message_loop_runner_->Run();
281 void WaitForCheckMediaPermission() {
282 if (checked_)
283 return;
284 check_message_loop_runner_ = new content::MessageLoopRunner;
285 check_message_loop_runner_->Run();
288 private:
289 bool requested_;
290 bool checked_;
291 scoped_refptr<content::MessageLoopRunner> request_message_loop_runner_;
292 scoped_refptr<content::MessageLoopRunner> check_message_loop_runner_;
294 DISALLOW_COPY_AND_ASSIGN(MockWebContentsDelegate);
297 // This class intercepts download request from the guest.
298 class MockDownloadWebContentsDelegate : public content::WebContentsDelegate {
299 public:
300 explicit MockDownloadWebContentsDelegate(
301 content::WebContentsDelegate* orig_delegate)
302 : orig_delegate_(orig_delegate),
303 waiting_for_decision_(false),
304 expect_allow_(false),
305 decision_made_(false),
306 last_download_allowed_(false) {}
307 ~MockDownloadWebContentsDelegate() override {}
309 void CanDownload(const GURL& url,
310 const std::string& request_method,
311 const base::Callback<void(bool)>& callback) override {
312 orig_delegate_->CanDownload(
313 url, request_method,
314 base::Bind(&MockDownloadWebContentsDelegate::DownloadDecided,
315 base::Unretained(this)));
318 void WaitForCanDownload(bool expect_allow) {
319 EXPECT_FALSE(waiting_for_decision_);
320 waiting_for_decision_ = true;
322 if (decision_made_) {
323 EXPECT_EQ(expect_allow, last_download_allowed_);
324 return;
327 expect_allow_ = expect_allow;
328 message_loop_runner_ = new content::MessageLoopRunner;
329 message_loop_runner_->Run();
332 void DownloadDecided(bool allow) {
333 EXPECT_FALSE(decision_made_);
334 decision_made_ = true;
336 if (waiting_for_decision_) {
337 EXPECT_EQ(expect_allow_, allow);
338 if (message_loop_runner_.get())
339 message_loop_runner_->Quit();
340 return;
342 last_download_allowed_ = allow;
345 void Reset() {
346 waiting_for_decision_ = false;
347 decision_made_ = false;
350 private:
351 content::WebContentsDelegate* orig_delegate_;
352 bool waiting_for_decision_;
353 bool expect_allow_;
354 bool decision_made_;
355 bool last_download_allowed_;
356 scoped_refptr<content::MessageLoopRunner> message_loop_runner_;
358 DISALLOW_COPY_AND_ASSIGN(MockDownloadWebContentsDelegate);
361 // TODO(wjmaclean): Fix this test class at some point so it can be re-enabled on
362 // the site isolation bots, and then look at re-enabling WebViewFocusTest when
363 // that happens.
364 // https://crbug.com/503751
365 class WebViewTest : public extensions::PlatformAppBrowserTest {
366 protected:
367 void SetUp() override {
368 if (UsesFakeSpeech()) {
369 // SpeechRecognition test specific SetUp.
370 fake_speech_recognition_manager_.reset(
371 new content::FakeSpeechRecognitionManager());
372 fake_speech_recognition_manager_->set_should_send_fake_response(true);
373 // Inject the fake manager factory so that the test result is returned to
374 // the web page.
375 content::SpeechRecognitionManager::SetManagerForTesting(
376 fake_speech_recognition_manager_.get());
378 extensions::PlatformAppBrowserTest::SetUp();
381 void TearDown() override {
382 if (UsesFakeSpeech()) {
383 // SpeechRecognition test specific TearDown.
384 content::SpeechRecognitionManager::SetManagerForTesting(NULL);
387 extensions::PlatformAppBrowserTest::TearDown();
390 void SetUpOnMainThread() override {
391 extensions::PlatformAppBrowserTest::SetUpOnMainThread();
392 const testing::TestInfo* const test_info =
393 testing::UnitTest::GetInstance()->current_test_info();
394 // Mock out geolocation for geolocation specific tests.
395 if (!strncmp(test_info->name(), "GeolocationAPI",
396 strlen("GeolocationAPI"))) {
397 ui_test_utils::OverrideGeolocation(10, 20);
401 void SetUpCommandLine(base::CommandLine* command_line) override {
402 command_line->AppendSwitch(switches::kUseFakeDeviceForMediaStream);
403 command_line->AppendSwitchASCII(switches::kJavaScriptFlags, "--expose-gc");
405 extensions::PlatformAppBrowserTest::SetUpCommandLine(command_line);
408 // Handles |request| by serving a redirect response if the |User-Agent| is
409 // foobar.
410 static scoped_ptr<net::test_server::HttpResponse> UserAgentResponseHandler(
411 const std::string& path,
412 const GURL& redirect_target,
413 const net::test_server::HttpRequest& request) {
414 if (!base::StartsWith(path, request.relative_url,
415 base::CompareCase::SENSITIVE))
416 return scoped_ptr<net::test_server::HttpResponse>();
418 std::map<std::string, std::string>::const_iterator it =
419 request.headers.find("User-Agent");
420 EXPECT_TRUE(it != request.headers.end());
421 if (!base::StartsWith("foobar", it->second,
422 base::CompareCase::SENSITIVE))
423 return scoped_ptr<net::test_server::HttpResponse>();
425 scoped_ptr<net::test_server::BasicHttpResponse> http_response(
426 new net::test_server::BasicHttpResponse);
427 http_response->set_code(net::HTTP_MOVED_PERMANENTLY);
428 http_response->AddCustomHeader("Location", redirect_target.spec());
429 return http_response.Pass();
432 // Handles |request| by serving a redirect response.
433 static scoped_ptr<net::test_server::HttpResponse> RedirectResponseHandler(
434 const std::string& path,
435 const GURL& redirect_target,
436 const net::test_server::HttpRequest& request) {
437 if (!base::StartsWith(path, request.relative_url,
438 base::CompareCase::SENSITIVE))
439 return scoped_ptr<net::test_server::HttpResponse>();
441 scoped_ptr<net::test_server::BasicHttpResponse> http_response(
442 new net::test_server::BasicHttpResponse);
443 http_response->set_code(net::HTTP_MOVED_PERMANENTLY);
444 http_response->AddCustomHeader("Location", redirect_target.spec());
445 return http_response.Pass();
448 // Handles |request| by serving an empty response.
449 static scoped_ptr<net::test_server::HttpResponse> EmptyResponseHandler(
450 const std::string& path,
451 const net::test_server::HttpRequest& request) {
452 if (base::StartsWith(path, request.relative_url,
453 base::CompareCase::SENSITIVE))
454 return scoped_ptr<net::test_server::HttpResponse>(new EmptyHttpResponse);
456 return scoped_ptr<net::test_server::HttpResponse>();
459 // Handles |request| by serving cache-able response.
460 static scoped_ptr<net::test_server::HttpResponse> CacheControlResponseHandler(
461 const std::string& path,
462 const net::test_server::HttpRequest& request) {
463 if (!base::StartsWith(path, request.relative_url,
464 base::CompareCase::SENSITIVE))
465 return scoped_ptr<net::test_server::HttpResponse>();
467 scoped_ptr<net::test_server::BasicHttpResponse> http_response(
468 new net::test_server::BasicHttpResponse);
469 http_response->AddCustomHeader("Cache-control", "max-age=3600");
470 http_response->set_content_type("text/plain");
471 http_response->set_content("dummy text");
472 return http_response.Pass();
475 // Shortcut to return the current MenuManager.
476 extensions::MenuManager* menu_manager() {
477 return extensions::MenuManager::Get(browser()->profile());
480 // This gets all the items that any extension has registered for possible
481 // inclusion in context menus.
482 MenuItem::List GetItems() {
483 MenuItem::List result;
484 std::set<MenuItem::ExtensionKey> extension_ids =
485 menu_manager()->ExtensionIds();
486 std::set<MenuItem::ExtensionKey>::iterator i;
487 for (i = extension_ids.begin(); i != extension_ids.end(); ++i) {
488 const MenuItem::List* list = menu_manager()->MenuItems(*i);
489 result.insert(result.end(), list->begin(), list->end());
491 return result;
494 enum TestServer {
495 NEEDS_TEST_SERVER,
496 NO_TEST_SERVER
499 void TestHelper(const std::string& test_name,
500 const std::string& app_location,
501 TestServer test_server) {
502 // For serving guest pages.
503 if (test_server == NEEDS_TEST_SERVER) {
504 if (!StartEmbeddedTestServer()) {
505 LOG(ERROR) << "FAILED TO START TEST SERVER.";
506 return;
508 embedded_test_server()->RegisterRequestHandler(
509 base::Bind(&WebViewTest::RedirectResponseHandler,
510 kRedirectResponsePath,
511 embedded_test_server()->GetURL(kRedirectResponseFullPath)));
513 embedded_test_server()->RegisterRequestHandler(
514 base::Bind(&WebViewTest::EmptyResponseHandler, kEmptyResponsePath));
516 embedded_test_server()->RegisterRequestHandler(
517 base::Bind(
518 &WebViewTest::UserAgentResponseHandler,
519 kUserAgentRedirectResponsePath,
520 embedded_test_server()->GetURL(kRedirectResponseFullPath)));
522 embedded_test_server()->RegisterRequestHandler(base::Bind(
523 &WebViewTest::CacheControlResponseHandler, kCacheResponsePath));
526 LoadAndLaunchPlatformApp(app_location.c_str(), "Launched");
528 // Flush any pending events to make sure we start with a clean slate.
529 content::RunAllPendingInMessageLoop();
531 content::WebContents* embedder_web_contents =
532 GetFirstAppWindowWebContents();
533 if (!embedder_web_contents) {
534 LOG(ERROR) << "UNABLE TO FIND EMBEDDER WEB CONTENTS.";
535 return;
538 ExtensionTestMessageListener done_listener("TEST_PASSED", false);
539 done_listener.set_failure_message("TEST_FAILED");
540 if (!content::ExecuteScript(
541 embedder_web_contents,
542 base::StringPrintf("runTest('%s')", test_name.c_str()))) {
543 LOG(ERROR) << "UNABLE TO START TEST.";
544 return;
546 ASSERT_TRUE(done_listener.WaitUntilSatisfied());
549 content::WebContents* LoadGuest(const std::string& guest_path,
550 const std::string& app_path) {
551 GURL::Replacements replace_host;
552 replace_host.SetHostStr("localhost");
554 GURL guest_url = embedded_test_server()->GetURL(guest_path);
555 guest_url = guest_url.ReplaceComponents(replace_host);
557 ui_test_utils::UrlLoadObserver guest_observer(
558 guest_url, content::NotificationService::AllSources());
560 LoadAndLaunchPlatformApp(app_path.c_str(), "guest-loaded");
562 guest_observer.Wait();
563 content::Source<content::NavigationController> source =
564 guest_observer.source();
565 EXPECT_TRUE(source->GetWebContents()->GetRenderProcessHost()->
566 IsForGuestsOnly());
568 content::WebContents* guest_web_contents = source->GetWebContents();
569 return guest_web_contents;
572 // Helper to load interstitial page in a <webview>.
573 void InterstitialTeardownTestHelper() {
574 // Start a HTTPS server so we can load an interstitial page inside guest.
575 net::SpawnedTestServer::SSLOptions ssl_options;
576 ssl_options.server_certificate =
577 net::SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME;
578 net::SpawnedTestServer https_server(
579 net::SpawnedTestServer::TYPE_HTTPS, ssl_options,
580 base::FilePath(FILE_PATH_LITERAL("chrome/test/data")));
581 ASSERT_TRUE(https_server.Start());
583 net::HostPortPair host_and_port = https_server.host_port_pair();
585 LoadAndLaunchPlatformApp("web_view/interstitial_teardown",
586 "EmbedderLoaded");
588 // Now load the guest.
589 content::WebContents* embedder_web_contents =
590 GetFirstAppWindowWebContents();
591 ExtensionTestMessageListener second("GuestAddedToDom", false);
592 EXPECT_TRUE(content::ExecuteScript(
593 embedder_web_contents,
594 base::StringPrintf("loadGuest(%d);\n", host_and_port.port())));
595 ASSERT_TRUE(second.WaitUntilSatisfied());
597 // Wait for interstitial page to be shown in guest.
598 content::WebContents* guest_web_contents =
599 GetGuestViewManager()->WaitForSingleGuestCreated();
600 ASSERT_TRUE(guest_web_contents->GetRenderProcessHost()->IsForGuestsOnly());
601 content::WaitForInterstitialAttach(guest_web_contents);
604 // Runs media_access/allow tests.
605 void MediaAccessAPIAllowTestHelper(const std::string& test_name);
607 // Runs media_access/deny tests, each of them are run separately otherwise
608 // they timeout (mostly on Windows).
609 void MediaAccessAPIDenyTestHelper(const std::string& test_name) {
610 ASSERT_TRUE(StartEmbeddedTestServer()); // For serving guest pages.
611 LoadAndLaunchPlatformApp("web_view/media_access/deny", "loaded");
613 content::WebContents* embedder_web_contents =
614 GetFirstAppWindowWebContents();
615 ASSERT_TRUE(embedder_web_contents);
617 ExtensionTestMessageListener test_run_listener("PASSED", false);
618 test_run_listener.set_failure_message("FAILED");
619 EXPECT_TRUE(
620 content::ExecuteScript(
621 embedder_web_contents,
622 base::StringPrintf("startDenyTest('%s')", test_name.c_str())));
623 ASSERT_TRUE(test_run_listener.WaitUntilSatisfied());
626 // Loads an app with a <webview> in it, returns once a guest is created.
627 void LoadAppWithGuest(const std::string& app_path) {
628 ExtensionTestMessageListener launched_listener("WebViewTest.LAUNCHED",
629 false);
630 launched_listener.set_failure_message("WebViewTest.FAILURE");
631 LoadAndLaunchPlatformApp(app_path.c_str(), &launched_listener);
633 guest_web_contents_ = GetGuestViewManager()->WaitForSingleGuestCreated();
636 void SendMessageToEmbedder(const std::string& message) {
637 EXPECT_TRUE(
638 content::ExecuteScript(
639 GetEmbedderWebContents(),
640 base::StringPrintf("onAppCommand('%s');", message.c_str())));
643 void SendMessageToGuestAndWait(const std::string& message,
644 const std::string& wait_message) {
645 scoped_ptr<ExtensionTestMessageListener> listener;
646 if (!wait_message.empty()) {
647 listener.reset(new ExtensionTestMessageListener(wait_message, false));
650 EXPECT_TRUE(
651 content::ExecuteScript(
652 GetGuestWebContents(),
653 base::StringPrintf("onAppCommand('%s');", message.c_str())));
655 if (listener) {
656 ASSERT_TRUE(listener->WaitUntilSatisfied());
660 void OpenContextMenu(content::WebContents* web_contents) {
661 blink::WebMouseEvent mouse_event;
662 mouse_event.type = blink::WebInputEvent::MouseDown;
663 mouse_event.button = blink::WebMouseEvent::ButtonRight;
664 mouse_event.x = 1;
665 mouse_event.y = 1;
666 web_contents->GetRenderViewHost()->ForwardMouseEvent(mouse_event);
667 mouse_event.type = blink::WebInputEvent::MouseUp;
668 web_contents->GetRenderViewHost()->ForwardMouseEvent(mouse_event);
671 content::WebContents* GetGuestWebContents() {
672 return guest_web_contents_;
675 content::WebContents* GetEmbedderWebContents() {
676 if (!embedder_web_contents_) {
677 embedder_web_contents_ = GetFirstAppWindowWebContents();
679 return embedder_web_contents_;
682 TestGuestViewManager* GetGuestViewManager() {
683 TestGuestViewManager* manager = static_cast<TestGuestViewManager*>(
684 TestGuestViewManager::FromBrowserContext(browser()->profile()));
685 // TestGuestViewManager::WaitForSingleGuestCreated may and will get called
686 // before a guest is created.
687 if (!manager) {
688 manager = static_cast<TestGuestViewManager*>(
689 GuestViewManager::CreateWithDelegate(
690 browser()->profile(),
691 ExtensionsAPIClient::Get()->CreateGuestViewManagerDelegate(
692 browser()->profile())));
694 return manager;
697 WebViewTest() : guest_web_contents_(NULL),
698 embedder_web_contents_(NULL) {
699 GuestViewManager::set_factory_for_testing(&factory_);
702 protected:
703 scoped_refptr<content::FrameWatcher> frame_watcher_;
705 private:
706 bool UsesFakeSpeech() {
707 const testing::TestInfo* const test_info =
708 testing::UnitTest::GetInstance()->current_test_info();
710 // SpeechRecognition test specific SetUp.
711 return !strcmp(test_info->name(),
712 "SpeechRecognitionAPI_HasPermissionAllow");
715 scoped_ptr<content::FakeSpeechRecognitionManager>
716 fake_speech_recognition_manager_;
718 TestGuestViewManagerFactory factory_;
719 // Note that these are only set if you launch app using LoadAppWithGuest().
720 content::WebContents* guest_web_contents_;
721 content::WebContents* embedder_web_contents_;
724 // The following test suits are created to group tests based on specific
725 // features of <webview>.
726 // These features current would not work with --site-per-process and is
727 // disabled on site isolation FYI bots.
728 class WebViewNewWindowTest : public WebViewTest {};
729 class WebViewSizeTest : public WebViewTest {};
730 class WebViewSpeechAPITest : public WebViewTest {};
731 class WebViewVisibilityTest : public WebViewTest {};
733 // Test suite that containts tests that are meant to run with and without
734 // --site-per-process.
735 class WebViewCommonTest : public extensions::PlatformAppBrowserTest {};
737 class WebViewDPITest : public WebViewTest {
738 protected:
739 void SetUpCommandLine(base::CommandLine* command_line) override {
740 WebViewTest::SetUpCommandLine(command_line);
741 command_line->AppendSwitchASCII(switches::kForceDeviceScaleFactor,
742 base::StringPrintf("%f", scale()));
745 static float scale() { return 2.0f; }
748 // This test verifies that hiding the guest triggers WebContents::WasHidden().
749 IN_PROC_BROWSER_TEST_F(WebViewVisibilityTest, GuestVisibilityChanged) {
750 LoadAppWithGuest("web_view/visibility_changed");
752 scoped_refptr<content::MessageLoopRunner> loop_runner(
753 new content::MessageLoopRunner);
754 WebContentsHiddenObserver observer(GetGuestWebContents(),
755 loop_runner->QuitClosure());
757 // Handled in platform_apps/web_view/visibility_changed/main.js
758 SendMessageToEmbedder("hide-guest");
759 if (!observer.hidden_observed())
760 loop_runner->Run();
763 // This test verifies that hiding the embedder also hides the guest.
764 IN_PROC_BROWSER_TEST_F(WebViewVisibilityTest, EmbedderVisibilityChanged) {
765 LoadAppWithGuest("web_view/visibility_changed");
767 scoped_refptr<content::MessageLoopRunner> loop_runner(
768 new content::MessageLoopRunner);
769 WebContentsHiddenObserver observer(GetGuestWebContents(),
770 loop_runner->QuitClosure());
772 // Handled in platform_apps/web_view/visibility_changed/main.js
773 SendMessageToEmbedder("hide-embedder");
774 if (!observer.hidden_observed())
775 loop_runner->Run();
778 // This test verifies that reloading the embedder reloads the guest (and doest
779 // not crash).
780 IN_PROC_BROWSER_TEST_F(WebViewTest, ReloadEmbedder) {
781 // Just load a guest from other test, we do not want to add a separate
782 // platform_app for this test.
783 LoadAppWithGuest("web_view/visibility_changed");
785 ExtensionTestMessageListener launched_again_listener("WebViewTest.LAUNCHED",
786 false);
787 GetEmbedderWebContents()->GetController().Reload(false);
788 ASSERT_TRUE(launched_again_listener.WaitUntilSatisfied());
791 IN_PROC_BROWSER_TEST_F(WebViewTest, AcceptTouchEvents) {
792 LoadAppWithGuest("web_view/accept_touch_events");
794 content::RenderViewHost* embedder_rvh =
795 GetEmbedderWebContents()->GetRenderViewHost();
797 bool embedder_has_touch_handler =
798 content::RenderViewHostTester::HasTouchEventHandler(embedder_rvh);
799 EXPECT_FALSE(embedder_has_touch_handler);
801 SendMessageToGuestAndWait("install-touch-handler", "installed-touch-handler");
803 // Note that we need to wait for the installed/registered touch handler to
804 // appear in browser process before querying |embedder_rvh|.
805 // In practice, since we do a roundrtip from browser process to guest and
806 // back, this is sufficient.
807 embedder_has_touch_handler =
808 content::RenderViewHostTester::HasTouchEventHandler(embedder_rvh);
809 EXPECT_TRUE(embedder_has_touch_handler);
811 SendMessageToGuestAndWait("uninstall-touch-handler",
812 "uninstalled-touch-handler");
813 // Same as the note above about waiting.
814 embedder_has_touch_handler =
815 content::RenderViewHostTester::HasTouchEventHandler(embedder_rvh);
816 EXPECT_FALSE(embedder_has_touch_handler);
819 // This test ensures JavaScript errors ("Cannot redefine property") do not
820 // happen when a <webview> is removed from DOM and added back.
821 IN_PROC_BROWSER_TEST_F(WebViewTest,
822 AddRemoveWebView_AddRemoveWebView) {
823 ASSERT_TRUE(StartEmbeddedTestServer()); // For serving guest pages.
824 ASSERT_TRUE(RunPlatformAppTest("platform_apps/web_view/addremove"))
825 << message_;
828 IN_PROC_BROWSER_TEST_F(WebViewSizeTest, AutoSize) {
829 #if defined(OS_WIN)
830 // Flaky on XP bot http://crbug.com/299507
831 if (base::win::GetVersion() <= base::win::VERSION_XP)
832 return;
833 #endif
835 ASSERT_TRUE(RunPlatformAppTest("platform_apps/web_view/autosize"))
836 << message_;
839 // Test for http://crbug.com/419611.
840 IN_PROC_BROWSER_TEST_F(WebViewTest, DisplayNoneSetSrc) {
841 LoadAndLaunchPlatformApp("web_view/display_none_set_src",
842 "WebViewTest.LAUNCHED");
843 // Navigate the guest while it's in "display: none" state.
844 SendMessageToEmbedder("navigate-guest");
845 GetGuestViewManager()->WaitForSingleGuestCreated();
847 // Now attempt to navigate the guest again.
848 SendMessageToEmbedder("navigate-guest");
850 ExtensionTestMessageListener test_passed_listener("WebViewTest.PASSED",
851 false);
852 // Making the guest visible would trigger loadstop.
853 SendMessageToEmbedder("show-guest");
854 EXPECT_TRUE(test_passed_listener.WaitUntilSatisfied());
857 // Checks that {allFrames: true} injects script correctly to subframes
858 // inside <webview>.
859 IN_PROC_BROWSER_TEST_F(WebViewTest, ExecuteScript) {
860 ASSERT_TRUE(RunPlatformAppTestWithArg(
861 "platform_apps/web_view/common", "execute_script")) << message_;
864 // http://crbug.com/326332
865 IN_PROC_BROWSER_TEST_F(WebViewSizeTest,
866 DISABLED_Shim_TestAutosizeAfterNavigation) {
867 TestHelper("testAutosizeAfterNavigation", "web_view/shim", NO_TEST_SERVER);
870 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestAllowTransparencyAttribute) {
871 TestHelper("testAllowTransparencyAttribute", "web_view/shim", NO_TEST_SERVER);
874 IN_PROC_BROWSER_TEST_F(WebViewDPITest, Shim_TestAutosizeHeight) {
875 TestHelper("testAutosizeHeight", "web_view/shim", NO_TEST_SERVER);
878 IN_PROC_BROWSER_TEST_F(WebViewSizeTest, Shim_TestAutosizeHeight) {
879 TestHelper("testAutosizeHeight", "web_view/shim", NO_TEST_SERVER);
882 IN_PROC_BROWSER_TEST_F(WebViewDPITest, Shim_TestAutosizeBeforeNavigation) {
883 TestHelper("testAutosizeBeforeNavigation", "web_view/shim", NO_TEST_SERVER);
886 IN_PROC_BROWSER_TEST_F(WebViewSizeTest, Shim_TestAutosizeBeforeNavigation) {
887 TestHelper("testAutosizeBeforeNavigation", "web_view/shim", NO_TEST_SERVER);
890 IN_PROC_BROWSER_TEST_F(WebViewDPITest, Shim_TestAutosizeRemoveAttributes) {
891 TestHelper("testAutosizeRemoveAttributes", "web_view/shim", NO_TEST_SERVER);
894 IN_PROC_BROWSER_TEST_F(WebViewSizeTest, Shim_TestAutosizeRemoveAttributes) {
895 TestHelper("testAutosizeRemoveAttributes", "web_view/shim", NO_TEST_SERVER);
898 // This test is disabled due to being flaky. http://crbug.com/282116
899 IN_PROC_BROWSER_TEST_F(WebViewSizeTest,
900 DISABLED_Shim_TestAutosizeWithPartialAttributes) {
901 TestHelper("testAutosizeWithPartialAttributes",
902 "web_view/shim",
903 NO_TEST_SERVER);
906 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestAPIMethodExistence) {
907 TestHelper("testAPIMethodExistence", "web_view/shim", NO_TEST_SERVER);
910 // Tests the existence of WebRequest API event objects on the request
911 // object, on the webview element, and hanging directly off webview.
912 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestWebRequestAPIExistence) {
913 TestHelper("testWebRequestAPIExistence", "web_view/shim", NO_TEST_SERVER);
916 // Tests that addListener call succeeds on webview's WebRequest API events.
917 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestWebRequestAPIAddListener) {
918 TestHelper("testWebRequestAPIAddListener", "web_view/shim", NO_TEST_SERVER);
921 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestWebRequestAPIErrorOccurred) {
922 TestHelper("testWebRequestAPIErrorOccurred", "web_view/shim", NO_TEST_SERVER);
925 // http://crbug.com/315920
926 #if defined(GOOGLE_CHROME_BUILD) && (defined(OS_WIN) || defined(OS_LINUX))
927 #define MAYBE_Shim_TestChromeExtensionURL DISABLED_Shim_TestChromeExtensionURL
928 #else
929 #define MAYBE_Shim_TestChromeExtensionURL Shim_TestChromeExtensionURL
930 #endif
931 IN_PROC_BROWSER_TEST_F(WebViewTest, MAYBE_Shim_TestChromeExtensionURL) {
932 TestHelper("testChromeExtensionURL", "web_view/shim", NO_TEST_SERVER);
935 // http://crbug.com/315920
936 #if defined(GOOGLE_CHROME_BUILD) && (defined(OS_WIN) || defined(OS_LINUX))
937 #define MAYBE_Shim_TestChromeExtensionRelativePath \
938 DISABLED_Shim_TestChromeExtensionRelativePath
939 #else
940 #define MAYBE_Shim_TestChromeExtensionRelativePath \
941 Shim_TestChromeExtensionRelativePath
942 #endif
943 IN_PROC_BROWSER_TEST_F(WebViewTest,
944 MAYBE_Shim_TestChromeExtensionRelativePath) {
945 TestHelper("testChromeExtensionRelativePath",
946 "web_view/shim",
947 NO_TEST_SERVER);
950 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestDisplayNoneWebviewLoad) {
951 TestHelper("testDisplayNoneWebviewLoad", "web_view/shim", NO_TEST_SERVER);
954 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestDisplayNoneWebviewRemoveChild) {
955 TestHelper("testDisplayNoneWebviewRemoveChild",
956 "web_view/shim", NO_TEST_SERVER);
959 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestDisplayBlock) {
960 TestHelper("testDisplayBlock", "web_view/shim", NO_TEST_SERVER);
963 IN_PROC_BROWSER_TEST_F(WebViewTest,
964 Shim_TestInlineScriptFromAccessibleResources) {
965 TestHelper("testInlineScriptFromAccessibleResources",
966 "web_view/shim",
967 NO_TEST_SERVER);
970 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestInvalidChromeExtensionURL) {
971 TestHelper("testInvalidChromeExtensionURL", "web_view/shim", NO_TEST_SERVER);
974 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestEventName) {
975 TestHelper("testEventName", "web_view/shim", NO_TEST_SERVER);
978 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestOnEventProperty) {
979 TestHelper("testOnEventProperties", "web_view/shim", NO_TEST_SERVER);
982 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestLoadProgressEvent) {
983 TestHelper("testLoadProgressEvent", "web_view/shim", NO_TEST_SERVER);
986 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestDestroyOnEventListener) {
987 TestHelper("testDestroyOnEventListener", "web_view/shim", NO_TEST_SERVER);
990 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestCannotMutateEventName) {
991 TestHelper("testCannotMutateEventName", "web_view/shim", NO_TEST_SERVER);
994 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestPartitionChangeAfterNavigation) {
995 TestHelper("testPartitionChangeAfterNavigation",
996 "web_view/shim",
997 NO_TEST_SERVER);
1000 IN_PROC_BROWSER_TEST_F(WebViewTest,
1001 Shim_TestPartitionRemovalAfterNavigationFails) {
1002 TestHelper("testPartitionRemovalAfterNavigationFails",
1003 "web_view/shim",
1004 NO_TEST_SERVER);
1007 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestAddContentScript) {
1008 TestHelper("testAddContentScript", "web_view/shim", NEEDS_TEST_SERVER);
1011 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestAddMultipleContentScripts) {
1012 TestHelper("testAddMultipleContentScripts", "web_view/shim",
1013 NEEDS_TEST_SERVER);
1016 IN_PROC_BROWSER_TEST_F(
1017 WebViewTest,
1018 Shim_TestAddContentScriptWithSameNameShouldOverwriteTheExistingOne) {
1019 TestHelper("testAddContentScriptWithSameNameShouldOverwriteTheExistingOne",
1020 "web_view/shim", NEEDS_TEST_SERVER);
1023 IN_PROC_BROWSER_TEST_F(
1024 WebViewTest,
1025 Shim_TestAddContentScriptToOneWebViewShouldNotInjectToTheOtherWebView) {
1026 TestHelper("testAddContentScriptToOneWebViewShouldNotInjectToTheOtherWebView",
1027 "web_view/shim", NEEDS_TEST_SERVER);
1030 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestAddAndRemoveContentScripts) {
1031 TestHelper("testAddAndRemoveContentScripts", "web_view/shim",
1032 NEEDS_TEST_SERVER);
1035 IN_PROC_BROWSER_TEST_F(WebViewNewWindowTest,
1036 Shim_TestAddContentScriptsWithNewWindowAPI) {
1037 TestHelper("testAddContentScriptsWithNewWindowAPI", "web_view/shim",
1038 NEEDS_TEST_SERVER);
1041 IN_PROC_BROWSER_TEST_F(
1042 WebViewTest,
1043 Shim_TestContentScriptIsInjectedAfterTerminateAndReloadWebView) {
1044 TestHelper("testContentScriptIsInjectedAfterTerminateAndReloadWebView",
1045 "web_view/shim", NEEDS_TEST_SERVER);
1048 IN_PROC_BROWSER_TEST_F(WebViewTest,
1049 Shim_TestContentScriptExistsAsLongAsWebViewTagExists) {
1050 TestHelper("testContentScriptExistsAsLongAsWebViewTagExists", "web_view/shim",
1051 NEEDS_TEST_SERVER);
1054 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestAddContentScriptWithCode) {
1055 TestHelper("testAddContentScriptWithCode", "web_view/shim",
1056 NEEDS_TEST_SERVER);
1059 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestExecuteScriptFail) {
1060 #if defined(OS_WIN)
1061 // Flaky on XP bot http://crbug.com/266185
1062 if (base::win::GetVersion() <= base::win::VERSION_XP)
1063 return;
1064 #endif
1066 TestHelper("testExecuteScriptFail", "web_view/shim", NEEDS_TEST_SERVER);
1069 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestExecuteScript) {
1070 TestHelper("testExecuteScript", "web_view/shim", NO_TEST_SERVER);
1073 IN_PROC_BROWSER_TEST_F(
1074 WebViewTest,
1075 Shim_TestExecuteScriptIsAbortedWhenWebViewSourceIsChanged) {
1076 TestHelper("testExecuteScriptIsAbortedWhenWebViewSourceIsChanged",
1077 "web_view/shim",
1078 NO_TEST_SERVER);
1081 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestTerminateAfterExit) {
1082 TestHelper("testTerminateAfterExit", "web_view/shim", NO_TEST_SERVER);
1085 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestAssignSrcAfterCrash) {
1086 TestHelper("testAssignSrcAfterCrash", "web_view/shim", NO_TEST_SERVER);
1089 IN_PROC_BROWSER_TEST_F(WebViewTest,
1090 Shim_TestNavOnConsecutiveSrcAttributeChanges) {
1091 TestHelper("testNavOnConsecutiveSrcAttributeChanges",
1092 "web_view/shim",
1093 NO_TEST_SERVER);
1096 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestNavOnSrcAttributeChange) {
1097 TestHelper("testNavOnSrcAttributeChange", "web_view/shim", NO_TEST_SERVER);
1100 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestNavigateAfterResize) {
1101 TestHelper("testNavigateAfterResize", "web_view/shim", NO_TEST_SERVER);
1104 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestNestedCrossOriginSubframes) {
1105 TestHelper("testNestedCrossOriginSubframes",
1106 "web_view/shim", NEEDS_TEST_SERVER);
1109 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestNestedSubframes) {
1110 TestHelper("testNestedSubframes", "web_view/shim", NO_TEST_SERVER);
1113 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestRemoveSrcAttribute) {
1114 TestHelper("testRemoveSrcAttribute", "web_view/shim", NO_TEST_SERVER);
1117 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestReassignSrcAttribute) {
1118 TestHelper("testReassignSrcAttribute", "web_view/shim", NO_TEST_SERVER);
1121 IN_PROC_BROWSER_TEST_F(WebViewNewWindowTest, Shim_TestNewWindow) {
1122 TestHelper("testNewWindow", "web_view/shim", NEEDS_TEST_SERVER);
1125 IN_PROC_BROWSER_TEST_F(WebViewNewWindowTest, Shim_TestNewWindowTwoListeners) {
1126 TestHelper("testNewWindowTwoListeners", "web_view/shim", NEEDS_TEST_SERVER);
1129 IN_PROC_BROWSER_TEST_F(WebViewNewWindowTest,
1130 Shim_TestNewWindowNoPreventDefault) {
1131 TestHelper("testNewWindowNoPreventDefault",
1132 "web_view/shim",
1133 NEEDS_TEST_SERVER);
1136 IN_PROC_BROWSER_TEST_F(WebViewNewWindowTest, Shim_TestNewWindowNoReferrerLink) {
1137 TestHelper("testNewWindowNoReferrerLink", "web_view/shim", NEEDS_TEST_SERVER);
1140 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestContentLoadEvent) {
1141 TestHelper("testContentLoadEvent", "web_view/shim", NO_TEST_SERVER);
1144 // TODO(fsamuel): Enable this test once <webview> can run in a detached state.
1145 IN_PROC_BROWSER_TEST_F(WebViewTest,
1146 Shim_TestContentLoadEventWithDisplayNone) {
1147 TestHelper("testContentLoadEventWithDisplayNone",
1148 "web_view/shim",
1149 NO_TEST_SERVER);
1152 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestDeclarativeWebRequestAPI) {
1153 TestHelper("testDeclarativeWebRequestAPI",
1154 "web_view/shim",
1155 NEEDS_TEST_SERVER);
1158 IN_PROC_BROWSER_TEST_F(WebViewTest,
1159 Shim_TestDeclarativeWebRequestAPISendMessage) {
1160 TestHelper("testDeclarativeWebRequestAPISendMessage",
1161 "web_view/shim",
1162 NEEDS_TEST_SERVER);
1165 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestWebRequestAPI) {
1166 TestHelper("testWebRequestAPI", "web_view/shim", NEEDS_TEST_SERVER);
1169 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestWebRequestAPIWithHeaders) {
1170 TestHelper("testWebRequestAPIWithHeaders",
1171 "web_view/shim",
1172 NEEDS_TEST_SERVER);
1175 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestWebRequestAPIGoogleProperty) {
1176 TestHelper("testWebRequestAPIGoogleProperty",
1177 "web_view/shim",
1178 NO_TEST_SERVER);
1181 IN_PROC_BROWSER_TEST_F(
1182 WebViewTest, Shim_TestWebRequestListenerSurvivesReparenting) {
1183 #if defined(OS_WIN)
1184 // Flaky on XP bot http://crbug.com/309451.
1185 if (base::win::GetVersion() <= base::win::VERSION_XP)
1186 return;
1187 #endif
1189 TestHelper("testWebRequestListenerSurvivesReparenting",
1190 "web_view/shim",
1191 NEEDS_TEST_SERVER);
1194 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestLoadStartLoadRedirect) {
1195 TestHelper("testLoadStartLoadRedirect", "web_view/shim", NEEDS_TEST_SERVER);
1198 IN_PROC_BROWSER_TEST_F(WebViewTest,
1199 Shim_TestLoadAbortChromeExtensionURLWrongPartition) {
1200 TestHelper("testLoadAbortChromeExtensionURLWrongPartition",
1201 "web_view/shim",
1202 NO_TEST_SERVER);
1205 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestLoadAbortEmptyResponse) {
1206 TestHelper("testLoadAbortEmptyResponse", "web_view/shim", NEEDS_TEST_SERVER);
1209 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestLoadAbortIllegalChromeURL) {
1210 TestHelper("testLoadAbortIllegalChromeURL",
1211 "web_view/shim",
1212 NO_TEST_SERVER);
1215 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestLoadAbortIllegalFileURL) {
1216 TestHelper("testLoadAbortIllegalFileURL", "web_view/shim", NO_TEST_SERVER);
1219 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestLoadAbortIllegalJavaScriptURL) {
1220 TestHelper("testLoadAbortIllegalJavaScriptURL",
1221 "web_view/shim",
1222 NO_TEST_SERVER);
1225 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestLoadAbortInvalidNavigation) {
1226 TestHelper("testLoadAbortInvalidNavigation", "web_view/shim", NO_TEST_SERVER);
1229 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestLoadAbortNonWebSafeScheme) {
1230 TestHelper("testLoadAbortNonWebSafeScheme", "web_view/shim", NO_TEST_SERVER);
1233 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestReload) {
1234 TestHelper("testReload", "web_view/shim", NO_TEST_SERVER);
1237 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestReloadAfterTerminate) {
1238 TestHelper("testReloadAfterTerminate", "web_view/shim", NO_TEST_SERVER);
1241 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestGetProcessId) {
1242 TestHelper("testGetProcessId", "web_view/shim", NO_TEST_SERVER);
1245 IN_PROC_BROWSER_TEST_F(WebViewVisibilityTest, Shim_TestHiddenBeforeNavigation) {
1246 TestHelper("testHiddenBeforeNavigation", "web_view/shim", NO_TEST_SERVER);
1249 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestRemoveWebviewOnExit) {
1250 ASSERT_TRUE(StartEmbeddedTestServer()); // For serving guest pages.
1252 // Launch the app and wait until it's ready to load a test.
1253 LoadAndLaunchPlatformApp("web_view/shim", "Launched");
1255 content::WebContents* embedder_web_contents = GetFirstAppWindowWebContents();
1256 ASSERT_TRUE(embedder_web_contents);
1258 GURL::Replacements replace_host;
1259 replace_host.SetHostStr("localhost");
1261 std::string guest_path(
1262 "/extensions/platform_apps/web_view/shim/empty_guest.html");
1263 GURL guest_url = embedded_test_server()->GetURL(guest_path);
1264 guest_url = guest_url.ReplaceComponents(replace_host);
1266 ui_test_utils::UrlLoadObserver guest_observer(
1267 guest_url, content::NotificationService::AllSources());
1269 // Run the test and wait until the guest WebContents is available and has
1270 // finished loading.
1271 ExtensionTestMessageListener guest_loaded_listener("guest-loaded", false);
1272 EXPECT_TRUE(content::ExecuteScript(
1273 embedder_web_contents,
1274 "runTest('testRemoveWebviewOnExit')"));
1275 guest_observer.Wait();
1277 content::Source<content::NavigationController> source =
1278 guest_observer.source();
1279 EXPECT_TRUE(source->GetWebContents()->GetRenderProcessHost()->
1280 IsForGuestsOnly());
1282 ASSERT_TRUE(guest_loaded_listener.WaitUntilSatisfied());
1284 content::WebContentsDestroyedWatcher destroyed_watcher(
1285 source->GetWebContents());
1287 // Tell the embedder to kill the guest.
1288 EXPECT_TRUE(content::ExecuteScript(
1289 embedder_web_contents,
1290 "removeWebviewOnExitDoCrash();"));
1292 // Wait until the guest WebContents is destroyed.
1293 destroyed_watcher.Wait();
1296 // Remove <webview> immediately after navigating it.
1297 // This is a regression test for http://crbug.com/276023.
1298 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestRemoveWebviewAfterNavigation) {
1299 TestHelper("testRemoveWebviewAfterNavigation",
1300 "web_view/shim",
1301 NO_TEST_SERVER);
1304 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestNavigationToExternalProtocol) {
1305 TestHelper("testNavigationToExternalProtocol",
1306 "web_view/shim",
1307 NO_TEST_SERVER);
1310 IN_PROC_BROWSER_TEST_F(WebViewSizeTest,
1311 Shim_TestResizeWebviewWithDisplayNoneResizesContent) {
1312 TestHelper("testResizeWebviewWithDisplayNoneResizesContent",
1313 "web_view/shim",
1314 NO_TEST_SERVER);
1317 IN_PROC_BROWSER_TEST_F(WebViewSizeTest, Shim_TestResizeWebviewResizesContent) {
1318 TestHelper("testResizeWebviewResizesContent",
1319 "web_view/shim",
1320 NO_TEST_SERVER);
1323 // This test makes sure the browser process does not crash if app is closed
1324 // while an interstitial page is being shown in guest.
1325 IN_PROC_BROWSER_TEST_F(WebViewTest, InterstitialTeardown) {
1326 #if defined(OS_WIN)
1327 // Flaky on XP bot http://crbug.com/297014
1328 if (base::win::GetVersion() <= base::win::VERSION_XP)
1329 return;
1330 #endif
1332 InterstitialTeardownTestHelper();
1334 // Now close the app while interstitial page being shown in guest.
1335 extensions::AppWindow* window = GetFirstAppWindow();
1336 window->GetBaseWindow()->Close();
1339 // This test makes sure the browser process does not crash if browser is shut
1340 // down while an interstitial page is being shown in guest.
1341 IN_PROC_BROWSER_TEST_F(WebViewTest, InterstitialTeardownOnBrowserShutdown) {
1342 #if defined(OS_WIN)
1343 // http://crbug.com/297014
1344 if (base::win::GetVersion() <= base::win::VERSION_XP)
1345 return;
1346 #endif
1348 InterstitialTeardownTestHelper();
1350 // Now close the app while interstitial page being shown in guest.
1351 extensions::AppWindow* window = GetFirstAppWindow();
1352 window->GetBaseWindow()->Close();
1354 // InterstitialPage is not destroyed immediately, so the
1355 // RenderWidgetHostViewGuest for it is still there, closing all
1356 // renderer processes will cause the RWHVGuest's RenderProcessGone()
1357 // shutdown path to be exercised.
1358 chrome::CloseAllBrowsers();
1361 IN_PROC_BROWSER_TEST_F(WebViewTest, ShimSrcAttribute) {
1362 ASSERT_TRUE(RunPlatformAppTest("platform_apps/web_view/src_attribute"))
1363 << message_;
1366 // This test verifies that prerendering has been disabled inside <webview>.
1367 // This test is here rather than in PrerenderBrowserTest for testing convenience
1368 // only. If it breaks then this is a bug in the prerenderer.
1369 IN_PROC_BROWSER_TEST_F(WebViewTest, NoPrerenderer) {
1370 ASSERT_TRUE(StartEmbeddedTestServer());
1371 content::WebContents* guest_web_contents =
1372 LoadGuest(
1373 "/extensions/platform_apps/web_view/noprerenderer/guest.html",
1374 "web_view/noprerenderer");
1375 ASSERT_TRUE(guest_web_contents != NULL);
1377 PrerenderLinkManager* prerender_link_manager =
1378 PrerenderLinkManagerFactory::GetForProfile(
1379 Profile::FromBrowserContext(guest_web_contents->GetBrowserContext()));
1380 ASSERT_TRUE(prerender_link_manager != NULL);
1381 EXPECT_TRUE(prerender_link_manager->IsEmpty());
1384 // Verify that existing <webview>'s are detected when the task manager starts
1385 // up.
1386 IN_PROC_BROWSER_TEST_F(WebViewTest, TaskManagerExistingWebView) {
1387 // This test is for the old implementation of the task manager. We must
1388 // explicitly disable the new one.
1389 task_manager::browsertest_util::EnableOldTaskManager();
1391 ASSERT_TRUE(StartEmbeddedTestServer());
1393 LoadGuest("/extensions/platform_apps/web_view/task_manager/guest.html",
1394 "web_view/task_manager");
1396 chrome::ShowTaskManager(browser()); // Show task manager AFTER guest loads.
1398 const char* guest_title = "WebViewed test content";
1399 const char* app_name = "<webview> task manager test";
1400 ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(1, MatchWebView(guest_title)));
1401 ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(1, MatchAboutBlankTab()));
1402 ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(1, MatchApp(app_name)));
1403 ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(1, MatchBackground(app_name)));
1405 ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(1, MatchAnyWebView()));
1406 ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(1, MatchAnyTab()));
1407 ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(1, MatchAnyApp()));
1408 ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(1, MatchAnyBackground()));
1411 // Verify that the task manager notices the creation of new <webview>'s.
1412 IN_PROC_BROWSER_TEST_F(WebViewTest, TaskManagerNewWebView) {
1413 // This test is for the old implementation of the task manager. We must
1414 // explicitly disable the new one.
1415 task_manager::browsertest_util::EnableOldTaskManager();
1417 ASSERT_TRUE(StartEmbeddedTestServer());
1419 chrome::ShowTaskManager(browser()); // Show task manager BEFORE guest loads.
1421 LoadGuest("/extensions/platform_apps/web_view/task_manager/guest.html",
1422 "web_view/task_manager");
1424 const char* guest_title = "WebViewed test content";
1425 const char* app_name = "<webview> task manager test";
1426 ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(1, MatchWebView(guest_title)));
1427 ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(1, MatchAboutBlankTab()));
1428 ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(1, MatchApp(app_name)));
1429 ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(1, MatchBackground(app_name)));
1431 ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(1, MatchAnyWebView()));
1432 ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(1, MatchAnyTab()));
1433 ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(1, MatchAnyApp()));
1434 ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(1, MatchAnyBackground()));
1437 // This tests cookie isolation for packaged apps with webview tags. It navigates
1438 // the main browser window to a page that sets a cookie and loads an app with
1439 // multiple webview tags. Each tag sets a cookie and the test checks the proper
1440 // storage isolation is enforced.
1441 IN_PROC_BROWSER_TEST_F(WebViewTest, CookieIsolation) {
1442 ASSERT_TRUE(StartEmbeddedTestServer());
1443 // Navigate the browser to a page which writes a sample cookie
1444 // The cookie is "testCookie=1"
1445 GURL set_cookie_url = embedded_test_server()->GetURL(
1446 "/extensions/platform_apps/web_view/cookie_isolation/set_cookie.html");
1447 GURL::Replacements replace_host;
1448 replace_host.SetHostStr("localhost");
1449 set_cookie_url = set_cookie_url.ReplaceComponents(replace_host);
1451 ui_test_utils::NavigateToURL(browser(), set_cookie_url);
1452 ASSERT_TRUE(RunPlatformAppTest("platform_apps/web_view/cookie_isolation"))
1453 << message_;
1454 // Finally, verify that the browser cookie has not changed.
1455 int cookie_size;
1456 std::string cookie_value;
1458 ui_test_utils::GetCookies(GURL("http://localhost"),
1459 browser()->tab_strip_model()->GetWebContentsAt(0),
1460 &cookie_size, &cookie_value);
1461 EXPECT_EQ("testCookie=1", cookie_value);
1464 // This tests that in-memory storage partitions are reset on browser restart,
1465 // but persistent ones maintain state for cookies and HTML5 storage.
1466 IN_PROC_BROWSER_TEST_F(WebViewTest, PRE_StoragePersistence) {
1467 ASSERT_TRUE(StartEmbeddedTestServer());
1468 // We don't care where the main browser is on this test.
1469 ui_test_utils::NavigateToURL(browser(), GURL("about:blank"));
1470 // Start the app for the pre-test.
1471 LoadAndLaunchPlatformApp("web_view/storage_persistence",
1472 "WebViewTest.LAUNCHED");
1474 // Send a message to run the PRE_StoragePersistence part of the test.
1475 SendMessageToEmbedder("run-pre-test");
1477 ExtensionTestMessageListener test_passed_listener("WebViewTest.PASSED",
1478 false);
1479 EXPECT_TRUE(test_passed_listener.WaitUntilSatisfied());
1482 // This is the post-reset portion of the StoragePersistence test. See
1483 // PRE_StoragePersistence for main comment.
1484 IN_PROC_BROWSER_TEST_F(WebViewTest, StoragePersistence) {
1485 ASSERT_TRUE(StartEmbeddedTestServer());
1486 // We don't care where the main browser is on this test.
1487 ui_test_utils::NavigateToURL(browser(), GURL("about:blank"));
1488 // Start the app for the pre-test.
1489 LoadAndLaunchPlatformApp("web_view/storage_persistence",
1490 "WebViewTest.LAUNCHED");
1492 // Send a message to run the StoragePersistence part of the test.
1493 SendMessageToEmbedder("run-test");
1495 ExtensionTestMessageListener test_passed_listener("WebViewTest.PASSED",
1496 false);
1497 EXPECT_TRUE(test_passed_listener.WaitUntilSatisfied());
1500 // This tests DOM storage isolation for packaged apps with webview tags. It
1501 // loads an app with multiple webview tags and each tag sets DOM storage
1502 // entries, which the test checks to ensure proper storage isolation is
1503 // enforced.
1504 IN_PROC_BROWSER_TEST_F(WebViewTest, DOMStorageIsolation) {
1505 ASSERT_TRUE(StartEmbeddedTestServer());
1507 GURL navigate_to_url = embedded_test_server()->GetURL(
1508 "/extensions/platform_apps/web_view/dom_storage_isolation/page.html");
1509 GURL::Replacements replace_host;
1510 replace_host.SetHostStr("localhost");
1511 navigate_to_url = navigate_to_url.ReplaceComponents(replace_host);
1513 ui_test_utils::NavigateToURL(browser(), navigate_to_url);
1514 ASSERT_TRUE(
1515 RunPlatformAppTest("platform_apps/web_view/dom_storage_isolation"));
1516 // Verify that the browser tab's local/session storage does not have the same
1517 // values which were stored by the webviews.
1518 std::string output;
1519 std::string get_local_storage(
1520 "window.domAutomationController.send("
1521 "window.localStorage.getItem('foo') || 'badval')");
1522 std::string get_session_storage(
1523 "window.domAutomationController.send("
1524 "window.localStorage.getItem('baz') || 'badval')");
1525 ASSERT_TRUE(ExecuteScriptAndExtractString(
1526 browser()->tab_strip_model()->GetWebContentsAt(0),
1527 get_local_storage.c_str(), &output));
1528 EXPECT_STREQ("badval", output.c_str());
1529 ASSERT_TRUE(ExecuteScriptAndExtractString(
1530 browser()->tab_strip_model()->GetWebContentsAt(0),
1531 get_session_storage.c_str(), &output));
1532 EXPECT_STREQ("badval", output.c_str());
1535 // This tests IndexedDB isolation for packaged apps with webview tags. It loads
1536 // an app with multiple webview tags and each tag creates an IndexedDB record,
1537 // which the test checks to ensure proper storage isolation is enforced.
1538 IN_PROC_BROWSER_TEST_F(WebViewTest, IndexedDBIsolation) {
1539 ASSERT_TRUE(StartEmbeddedTestServer());
1540 ASSERT_TRUE(RunPlatformAppTest(
1541 "platform_apps/web_view/isolation_indexeddb")) << message_;
1544 // This test ensures that closing app window on 'loadcommit' does not crash.
1545 // The test launches an app with guest and closes the window on loadcommit. It
1546 // then launches the app window again. The process is repeated 3 times.
1547 // http://crbug.com/291278
1548 #if defined(OS_WIN)
1549 #define MAYBE_CloseOnLoadcommit DISABLED_CloseOnLoadcommit
1550 #else
1551 #define MAYBE_CloseOnLoadcommit CloseOnLoadcommit
1552 #endif
1553 IN_PROC_BROWSER_TEST_F(WebViewTest, MAYBE_CloseOnLoadcommit) {
1554 LoadAndLaunchPlatformApp("web_view/close_on_loadcommit",
1555 "done-close-on-loadcommit");
1558 IN_PROC_BROWSER_TEST_F(WebViewTest, MediaAccessAPIDeny_TestDeny) {
1559 MediaAccessAPIDenyTestHelper("testDeny");
1562 IN_PROC_BROWSER_TEST_F(WebViewTest,
1563 MediaAccessAPIDeny_TestDenyThenAllowThrows) {
1564 MediaAccessAPIDenyTestHelper("testDenyThenAllowThrows");
1567 IN_PROC_BROWSER_TEST_F(WebViewTest,
1568 MediaAccessAPIDeny_TestDenyWithPreventDefault) {
1569 MediaAccessAPIDenyTestHelper("testDenyWithPreventDefault");
1572 IN_PROC_BROWSER_TEST_F(WebViewTest,
1573 MediaAccessAPIDeny_TestNoListenersImplyDeny) {
1574 MediaAccessAPIDenyTestHelper("testNoListenersImplyDeny");
1577 IN_PROC_BROWSER_TEST_F(WebViewTest,
1578 MediaAccessAPIDeny_TestNoPreventDefaultImpliesDeny) {
1579 MediaAccessAPIDenyTestHelper("testNoPreventDefaultImpliesDeny");
1582 void WebViewTest::MediaAccessAPIAllowTestHelper(const std::string& test_name) {
1583 ASSERT_TRUE(StartEmbeddedTestServer()); // For serving guest pages.
1584 LoadAndLaunchPlatformApp("web_view/media_access/allow", "Launched");
1586 content::WebContents* embedder_web_contents = GetFirstAppWindowWebContents();
1587 ASSERT_TRUE(embedder_web_contents);
1588 scoped_ptr<MockWebContentsDelegate> mock(new MockWebContentsDelegate());
1589 embedder_web_contents->SetDelegate(mock.get());
1591 ExtensionTestMessageListener done_listener("TEST_PASSED", false);
1592 done_listener.set_failure_message("TEST_FAILED");
1593 EXPECT_TRUE(
1594 content::ExecuteScript(
1595 embedder_web_contents,
1596 base::StringPrintf("startAllowTest('%s')",
1597 test_name.c_str())));
1598 ASSERT_TRUE(done_listener.WaitUntilSatisfied());
1600 mock->WaitForRequestMediaPermission();
1603 IN_PROC_BROWSER_TEST_F(WebViewTest, OpenURLFromTab_CurrentTab_Abort) {
1604 LoadAppWithGuest("web_view/simple");
1606 // Verify that OpenURLFromTab with a window disposition of CURRENT_TAB will
1607 // navigate the current <webview>.
1608 ExtensionTestMessageListener load_listener("WebViewTest.LOADSTOP", false);
1610 // Navigating to a file URL is forbidden inside a <webview>.
1611 content::OpenURLParams params(GURL("file://foo"),
1612 content::Referrer(),
1613 CURRENT_TAB,
1614 ui::PAGE_TRANSITION_AUTO_TOPLEVEL,
1615 true /* is_renderer_initiated */);
1616 GetGuestWebContents()->GetDelegate()->OpenURLFromTab(
1617 GetGuestWebContents(), params);
1619 ASSERT_TRUE(load_listener.WaitUntilSatisfied());
1621 // Verify that the <webview> ends up at about:blank.
1622 EXPECT_EQ(GURL(url::kAboutBlankURL),
1623 GetGuestWebContents()->GetLastCommittedURL());
1626 IN_PROC_BROWSER_TEST_F(WebViewNewWindowTest, OpenURLFromTab_NewWindow_Abort) {
1627 LoadAppWithGuest("web_view/simple");
1629 // Verify that OpenURLFromTab with a window disposition of NEW_BACKGROUND_TAB
1630 // will trigger the <webview>'s New Window API.
1631 ExtensionTestMessageListener new_window_listener(
1632 "WebViewTest.NEWWINDOW", false);
1634 // Navigating to a file URL is forbidden inside a <webview>.
1635 content::OpenURLParams params(GURL("file://foo"),
1636 content::Referrer(),
1637 NEW_BACKGROUND_TAB,
1638 ui::PAGE_TRANSITION_AUTO_TOPLEVEL,
1639 true /* is_renderer_initiated */);
1640 GetGuestWebContents()->GetDelegate()->OpenURLFromTab(
1641 GetGuestWebContents(), params);
1643 ASSERT_TRUE(new_window_listener.WaitUntilSatisfied());
1645 // Verify that a new guest was created.
1646 content::WebContents* new_guest_web_contents =
1647 GetGuestViewManager()->GetLastGuestCreated();
1648 EXPECT_NE(GetGuestWebContents(), new_guest_web_contents);
1650 // Verify that the new <webview> guest ends up at about:blank.
1651 EXPECT_EQ(GURL(url::kAboutBlankURL),
1652 new_guest_web_contents->GetLastCommittedURL());
1655 // This test executes the context menu command 'LanguageSettings' which will
1656 // load chrome://settings/languages in a browser window. This is a browser-
1657 // initiated operation and so we expect this to succeed if the embedder is
1658 // allowed to perform the operation.
1659 IN_PROC_BROWSER_TEST_F(WebViewTest, ContextMenuLanguageSettings) {
1660 LoadAppWithGuest("web_view/context_menus/basic");
1662 content::WebContents* guest_web_contents = GetGuestWebContents();
1663 content::WebContents* embedder = GetEmbedderWebContents();
1664 ASSERT_TRUE(embedder);
1666 // Create and build our test context menu.
1667 content::WebContentsAddedObserver web_contents_added_observer;
1669 GURL page_url("http://www.google.com");
1670 scoped_ptr<TestRenderViewContextMenu> menu(TestRenderViewContextMenu::Create(
1671 guest_web_contents, page_url, GURL(), GURL()));
1672 menu->ExecuteCommand(IDC_CONTENT_CONTEXT_LANGUAGE_SETTINGS, 0);
1674 content::WebContents* new_contents =
1675 web_contents_added_observer.GetWebContents();
1677 // Verify that a new WebContents has been created that is at the Language
1678 // Settings page.
1679 EXPECT_EQ(GURL("chrome://settings/languages"),
1680 new_contents->GetVisibleURL());
1683 IN_PROC_BROWSER_TEST_F(WebViewTest, ContextMenusAPI_Basic) {
1684 LoadAppWithGuest("web_view/context_menus/basic");
1686 content::WebContents* guest_web_contents = GetGuestWebContents();
1687 content::WebContents* embedder = GetEmbedderWebContents();
1688 ASSERT_TRUE(embedder);
1690 // 1. Basic property test.
1691 ExecuteScriptWaitForTitle(embedder, "checkProperties()", "ITEM_CHECKED");
1693 // 2. Create a menu item and wait for created callback to be called.
1694 ExecuteScriptWaitForTitle(embedder, "createMenuItem()", "ITEM_CREATED");
1696 // 3. Click the created item, wait for the click handlers to fire from JS.
1697 ExtensionTestMessageListener click_listener("ITEM_CLICKED", false);
1698 GURL page_url("http://www.google.com");
1699 // Create and build our test context menu.
1700 scoped_ptr<TestRenderViewContextMenu> menu(TestRenderViewContextMenu::Create(
1701 guest_web_contents, page_url, GURL(), GURL()));
1702 // Look for the extension item in the menu, and execute it.
1703 int command_id = ContextMenuMatcher::ConvertToExtensionsCustomCommandId(0);
1704 ASSERT_TRUE(menu->IsCommandIdEnabled(command_id));
1705 menu->ExecuteCommand(command_id, 0);
1706 // Wait for embedder's script to tell us its onclick fired, it does
1707 // chrome.test.sendMessage('ITEM_CLICKED')
1708 ASSERT_TRUE(click_listener.WaitUntilSatisfied());
1710 // 4. Update the item's title and verify.
1711 ExecuteScriptWaitForTitle(embedder, "updateMenuItem()", "ITEM_UPDATED");
1712 MenuItem::List items = GetItems();
1713 ASSERT_EQ(1u, items.size());
1714 MenuItem* item = items.at(0);
1715 EXPECT_EQ("new_title", item->title());
1717 // 5. Remove the item.
1718 ExecuteScriptWaitForTitle(embedder, "removeItem()", "ITEM_REMOVED");
1719 MenuItem::List items_after_removal = GetItems();
1720 ASSERT_EQ(0u, items_after_removal.size());
1722 // 6. Add some more items.
1723 ExecuteScriptWaitForTitle(
1724 embedder, "createThreeMenuItems()", "ITEM_MULTIPLE_CREATED");
1725 MenuItem::List items_after_insertion = GetItems();
1726 ASSERT_EQ(3u, items_after_insertion.size());
1728 // 7. Test removeAll().
1729 ExecuteScriptWaitForTitle(embedder, "removeAllItems()", "ITEM_ALL_REMOVED");
1730 MenuItem::List items_after_all_removal = GetItems();
1731 ASSERT_EQ(0u, items_after_all_removal.size());
1734 // Called in the TestContextMenu test to cancel the context menu after its
1735 // shown notification is received.
1736 static bool ContextMenuNotificationCallback(
1737 const content::NotificationSource& source,
1738 const content::NotificationDetails& details) {
1739 auto context_menu = content::Source<RenderViewContextMenu>(source).ptr();
1740 base::ThreadTaskRunnerHandle::Get()->PostTask(
1741 FROM_HERE, base::Bind(&RenderViewContextMenuBase::Cancel,
1742 base::Unretained(context_menu)));
1743 return true;
1746 IN_PROC_BROWSER_TEST_F(WebViewTest, ContextMenusAPI_PreventDefault) {
1747 LoadAppWithGuest("web_view/context_menus/basic");
1749 content::WebContents* guest_web_contents = GetGuestWebContents();
1750 content::WebContents* embedder = GetEmbedderWebContents();
1751 ASSERT_TRUE(embedder);
1753 // Add a preventDefault() call on context menu event so context menu
1754 // does not show up.
1755 ExtensionTestMessageListener prevent_default_listener(
1756 "WebViewTest.CONTEXT_MENU_DEFAULT_PREVENTED", false);
1757 EXPECT_TRUE(content::ExecuteScript(embedder, "registerPreventDefault()"));
1758 ContextMenuCallCountObserver context_menu_shown_observer;
1760 OpenContextMenu(guest_web_contents);
1762 EXPECT_TRUE(prevent_default_listener.WaitUntilSatisfied());
1763 // Expect the menu to not show up.
1764 EXPECT_EQ(0, context_menu_shown_observer.num_times_shown());
1766 // Now remove the preventDefault() and expect context menu to be shown.
1767 ExecuteScriptWaitForTitle(
1768 embedder, "removePreventDefault()", "PREVENT_DEFAULT_LISTENER_REMOVED");
1769 OpenContextMenu(guest_web_contents);
1771 // We expect to see a context menu for the second call to |OpenContextMenu|.
1772 context_menu_shown_observer.Wait();
1773 EXPECT_EQ(1, context_menu_shown_observer.num_times_shown());
1776 // Tests that a context menu is created when right-clicking in the webview. This
1777 // also tests that the 'contextmenu' event is handled correctly.
1778 IN_PROC_BROWSER_TEST_F(WebViewTest, TestContextMenu) {
1779 LoadAppWithGuest("web_view/context_menus/basic");
1780 content::WebContents* guest_web_contents = GetGuestWebContents();
1782 // Register an observer for the context menu.
1783 content::WindowedNotificationObserver menu_observer(
1784 chrome::NOTIFICATION_RENDER_VIEW_CONTEXT_MENU_SHOWN,
1785 base::Bind(ContextMenuNotificationCallback));
1787 OpenContextMenu(guest_web_contents);
1789 // Wait for the context menu to be visible.
1790 menu_observer.Wait();
1793 IN_PROC_BROWSER_TEST_F(WebViewTest, MediaAccessAPIAllow_TestAllow) {
1794 MediaAccessAPIAllowTestHelper("testAllow");
1797 IN_PROC_BROWSER_TEST_F(WebViewTest, MediaAccessAPIAllow_TestAllowAndThenDeny) {
1798 MediaAccessAPIAllowTestHelper("testAllowAndThenDeny");
1801 IN_PROC_BROWSER_TEST_F(WebViewTest, MediaAccessAPIAllow_TestAllowTwice) {
1802 MediaAccessAPIAllowTestHelper("testAllowTwice");
1805 IN_PROC_BROWSER_TEST_F(WebViewTest, MediaAccessAPIAllow_TestAllowAsync) {
1806 MediaAccessAPIAllowTestHelper("testAllowAsync");
1809 IN_PROC_BROWSER_TEST_F(WebViewTest, MediaAccessAPIAllow_TestCheck) {
1810 ASSERT_TRUE(StartEmbeddedTestServer()); // For serving guest pages.
1811 LoadAndLaunchPlatformApp("web_view/media_access/check", "Launched");
1813 content::WebContents* embedder_web_contents = GetFirstAppWindowWebContents();
1814 ASSERT_TRUE(embedder_web_contents);
1815 scoped_ptr<MockWebContentsDelegate> mock(new MockWebContentsDelegate());
1816 embedder_web_contents->SetDelegate(mock.get());
1818 ExtensionTestMessageListener done_listener("TEST_PASSED", false);
1819 done_listener.set_failure_message("TEST_FAILED");
1820 EXPECT_TRUE(
1821 content::ExecuteScript(
1822 embedder_web_contents,
1823 base::StringPrintf("startCheckTest('')")));
1824 ASSERT_TRUE(done_listener.WaitUntilSatisfied());
1826 mock->WaitForCheckMediaPermission();
1829 // Checks that window.screenX/screenY/screenLeft/screenTop works correctly for
1830 // guests.
1831 IN_PROC_BROWSER_TEST_F(WebViewTest, ScreenCoordinates) {
1832 ASSERT_TRUE(RunPlatformAppTestWithArg(
1833 "platform_apps/web_view/common", "screen_coordinates"))
1834 << message_;
1837 #if defined(OS_CHROMEOS)
1838 IN_PROC_BROWSER_TEST_F(WebViewTest, ChromeVoxInjection) {
1839 EXPECT_FALSE(
1840 chromeos::AccessibilityManager::Get()->IsSpokenFeedbackEnabled());
1842 chromeos::SpeechMonitor monitor;
1843 chromeos::AccessibilityManager::Get()->EnableSpokenFeedback(
1844 true, ui::A11Y_NOTIFICATION_NONE);
1845 EXPECT_TRUE(monitor.SkipChromeVoxEnabledMessage());
1847 ASSERT_TRUE(StartEmbeddedTestServer());
1848 content::WebContents* guest_web_contents = LoadGuest(
1849 "/extensions/platform_apps/web_view/chromevox_injection/guest.html",
1850 "web_view/chromevox_injection");
1851 ASSERT_TRUE(guest_web_contents);
1853 EXPECT_EQ("chrome vox test title", monitor.GetNextUtterance());
1855 #endif
1857 // Flaky on Windows. http://crbug.com/303966
1858 #if defined(OS_WIN)
1859 #define MAYBE_TearDownTest DISABLED_TearDownTest
1860 #else
1861 #define MAYBE_TearDownTest TearDownTest
1862 #endif
1863 IN_PROC_BROWSER_TEST_F(WebViewTest, MAYBE_TearDownTest) {
1864 const extensions::Extension* extension =
1865 LoadAndLaunchPlatformApp("web_view/simple", "WebViewTest.LAUNCHED");
1866 extensions::AppWindow* window = NULL;
1867 if (!GetAppWindowCount())
1868 window = CreateAppWindow(extension);
1869 else
1870 window = GetFirstAppWindow();
1871 CloseAppWindow(window);
1873 // Load the app again.
1874 LoadAndLaunchPlatformApp("web_view/simple", "WebViewTest.LAUNCHED");
1877 // In following GeolocationAPIEmbedderHasNoAccess* tests, embedder (i.e. the
1878 // platform app) does not have geolocation permission for this test.
1879 // No matter what the API does, geolocation permission would be denied.
1880 // Note that the test name prefix must be "GeolocationAPI".
1881 IN_PROC_BROWSER_TEST_F(WebViewTest, GeolocationAPIEmbedderHasNoAccessAllow) {
1882 TestHelper("testDenyDenies",
1883 "web_view/geolocation/embedder_has_no_permission",
1884 NEEDS_TEST_SERVER);
1887 IN_PROC_BROWSER_TEST_F(WebViewTest, GeolocationAPIEmbedderHasNoAccessDeny) {
1888 TestHelper("testDenyDenies",
1889 "web_view/geolocation/embedder_has_no_permission",
1890 NEEDS_TEST_SERVER);
1893 // In following GeolocationAPIEmbedderHasAccess* tests, embedder (i.e. the
1894 // platform app) has geolocation permission
1896 // Note that these test names must be "GeolocationAPI" prefixed (b/c we mock out
1897 // geolocation in this case).
1899 // Also note that these are run separately because OverrideGeolocation() doesn't
1900 // mock out geolocation for multiple navigator.geolocation calls properly and
1901 // the tests become flaky.
1903 // GeolocationAPI* test 1 of 3.
1904 // Currently disabled until crbug.com/526788 is fixed.
1905 IN_PROC_BROWSER_TEST_F(WebViewTest,
1906 DISABLED_GeolocationAPIEmbedderHasAccessAllow) {
1907 TestHelper("testAllow",
1908 "web_view/geolocation/embedder_has_permission",
1909 NEEDS_TEST_SERVER);
1912 // GeolocationAPI* test 2 of 3.
1913 IN_PROC_BROWSER_TEST_F(WebViewTest, GeolocationAPIEmbedderHasAccessDeny) {
1914 TestHelper("testDeny",
1915 "web_view/geolocation/embedder_has_permission",
1916 NEEDS_TEST_SERVER);
1919 // GeolocationAPI* test 3 of 3.
1920 // Currently disabled until crbug.com/526788 is fixed.
1921 IN_PROC_BROWSER_TEST_F(
1922 WebViewTest,
1923 DISABLED_GeolocationAPIEmbedderHasAccessMultipleBridgeIdAllow) {
1924 TestHelper("testMultipleBridgeIdAllow",
1925 "web_view/geolocation/embedder_has_permission",
1926 NEEDS_TEST_SERVER);
1929 // Tests that
1930 // BrowserPluginGeolocationPermissionContext::CancelGeolocationPermissionRequest
1931 // is handled correctly (and does not crash).
1932 IN_PROC_BROWSER_TEST_F(WebViewTest, GeolocationAPICancelGeolocation) {
1933 ASSERT_TRUE(StartEmbeddedTestServer()); // For serving guest pages.
1934 ASSERT_TRUE(RunPlatformAppTest(
1935 "platform_apps/web_view/geolocation/cancel_request")) << message_;
1938 IN_PROC_BROWSER_TEST_F(WebViewTest, DISABLED_GeolocationRequestGone) {
1939 ASSERT_TRUE(StartEmbeddedTestServer()); // For serving guest pages.
1940 ASSERT_TRUE(RunPlatformAppTest(
1941 "platform_apps/web_view/geolocation/geolocation_request_gone"))
1942 << message_;
1945 // In following FilesystemAPIRequestFromMainThread* tests, guest request
1946 // filesystem access from main thread of the guest.
1947 // FileSystemAPIRequestFromMainThread* test 1 of 3
1948 IN_PROC_BROWSER_TEST_F(WebViewTest, FileSystemAPIRequestFromMainThreadAllow) {
1949 TestHelper("testAllow", "web_view/filesystem/main", NEEDS_TEST_SERVER);
1952 // FileSystemAPIRequestFromMainThread* test 2 of 3.
1953 IN_PROC_BROWSER_TEST_F(WebViewTest, FileSystemAPIRequestFromMainThreadDeny) {
1954 TestHelper("testDeny", "web_view/filesystem/main", NEEDS_TEST_SERVER);
1957 // FileSystemAPIRequestFromMainThread* test 3 of 3.
1958 IN_PROC_BROWSER_TEST_F(WebViewTest,
1959 FileSystemAPIRequestFromMainThreadDefaultAllow) {
1960 TestHelper("testDefaultAllow", "web_view/filesystem/main", NEEDS_TEST_SERVER);
1963 // In following FilesystemAPIRequestFromWorker* tests, guest create a worker
1964 // to request filesystem access from worker thread.
1965 // FileSystemAPIRequestFromWorker* test 1 of 3
1966 IN_PROC_BROWSER_TEST_F(WebViewTest, FileSystemAPIRequestFromWorkerAllow) {
1967 TestHelper("testAllow", "web_view/filesystem/worker", NEEDS_TEST_SERVER);
1970 // FileSystemAPIRequestFromWorker* test 2 of 3.
1971 IN_PROC_BROWSER_TEST_F(WebViewTest, FileSystemAPIRequestFromWorkerDeny) {
1972 TestHelper("testDeny", "web_view/filesystem/worker", NEEDS_TEST_SERVER);
1975 // FileSystemAPIRequestFromWorker* test 3 of 3.
1976 IN_PROC_BROWSER_TEST_F(WebViewTest,
1977 FileSystemAPIRequestFromWorkerDefaultAllow) {
1978 TestHelper(
1979 "testDefaultAllow", "web_view/filesystem/worker", NEEDS_TEST_SERVER);
1982 // In following FilesystemAPIRequestFromSharedWorkerOfSingleWebViewGuest* tests,
1983 // embedder contains a single webview guest. The guest creates a shared worker
1984 // to request filesystem access from worker thread.
1985 // FileSystemAPIRequestFromSharedWorkerOfSingleWebViewGuest* test 1 of 3
1986 IN_PROC_BROWSER_TEST_F(
1987 WebViewTest,
1988 FileSystemAPIRequestFromSharedWorkerOfSingleWebViewGuestAllow) {
1989 TestHelper("testAllow",
1990 "web_view/filesystem/shared_worker/single",
1991 NEEDS_TEST_SERVER);
1994 // FileSystemAPIRequestFromSharedWorkerOfSingleWebViewGuest* test 2 of 3.
1995 IN_PROC_BROWSER_TEST_F(
1996 WebViewTest,
1997 FileSystemAPIRequestFromSharedWorkerOfSingleWebViewGuestDeny) {
1998 TestHelper("testDeny",
1999 "web_view/filesystem/shared_worker/single",
2000 NEEDS_TEST_SERVER);
2003 // FileSystemAPIRequestFromSharedWorkerOfSingleWebViewGuest* test 3 of 3.
2004 IN_PROC_BROWSER_TEST_F(
2005 WebViewTest,
2006 FileSystemAPIRequestFromSharedWorkerOfSingleWebViewGuestDefaultAllow) {
2007 TestHelper(
2008 "testDefaultAllow",
2009 "web_view/filesystem/shared_worker/single",
2010 NEEDS_TEST_SERVER);
2013 // In following FilesystemAPIRequestFromSharedWorkerOfMultiWebViewGuests* tests,
2014 // embedder contains mutiple webview guests. Each guest creates a shared worker
2015 // to request filesystem access from worker thread.
2016 // FileSystemAPIRequestFromSharedWorkerOfMultiWebViewGuests* test 1 of 3
2017 IN_PROC_BROWSER_TEST_F(
2018 WebViewTest,
2019 FileSystemAPIRequestFromSharedWorkerOfMultiWebViewGuestsAllow) {
2020 TestHelper("testAllow",
2021 "web_view/filesystem/shared_worker/multiple",
2022 NEEDS_TEST_SERVER);
2025 // FileSystemAPIRequestFromSharedWorkerOfMultiWebViewGuests* test 2 of 3.
2026 IN_PROC_BROWSER_TEST_F(
2027 WebViewTest,
2028 FileSystemAPIRequestFromSharedWorkerOfMultiWebViewGuestsDeny) {
2029 TestHelper("testDeny",
2030 "web_view/filesystem/shared_worker/multiple",
2031 NEEDS_TEST_SERVER);
2034 // FileSystemAPIRequestFromSharedWorkerOfMultiWebViewGuests* test 3 of 3.
2035 IN_PROC_BROWSER_TEST_F(
2036 WebViewTest,
2037 FileSystemAPIRequestFromSharedWorkerOfMultiWebViewGuestsDefaultAllow) {
2038 TestHelper(
2039 "testDefaultAllow",
2040 "web_view/filesystem/shared_worker/multiple",
2041 NEEDS_TEST_SERVER);
2044 IN_PROC_BROWSER_TEST_F(WebViewTest, ClearData) {
2045 #if defined(OS_WIN)
2046 // Flaky on XP bot http://crbug.com/282674
2047 if (base::win::GetVersion() <= base::win::VERSION_XP)
2048 return;
2049 #endif
2051 ASSERT_TRUE(StartEmbeddedTestServer()); // For serving guest pages.
2052 ASSERT_TRUE(RunPlatformAppTestWithArg(
2053 "platform_apps/web_view/common", "cleardata"))
2054 << message_;
2057 #if defined(OS_WIN)
2058 // Test is disabled on Windows because it fails often (~9% time)
2059 // http://crbug.com/489088
2060 #define MAYBE_ClearDataCache DISABLED_ClearDataCache
2061 #else
2062 #define MAYBE_ClearDataCache ClearDataCache
2063 #endif
2064 IN_PROC_BROWSER_TEST_F(WebViewTest, MAYBE_ClearDataCache) {
2065 TestHelper("testClearCache", "web_view/clear_data_cache", NEEDS_TEST_SERVER);
2068 IN_PROC_BROWSER_TEST_F(WebViewTest, ConsoleMessage) {
2069 ASSERT_TRUE(RunPlatformAppTestWithArg(
2070 "platform_apps/web_view/common", "console_messages"))
2071 << message_;
2074 IN_PROC_BROWSER_TEST_F(WebViewTest, DownloadPermission) {
2075 ASSERT_TRUE(StartEmbeddedTestServer()); // For serving guest pages.
2076 content::WebContents* guest_web_contents =
2077 LoadGuest("/extensions/platform_apps/web_view/download/guest.html",
2078 "web_view/download");
2079 ASSERT_TRUE(guest_web_contents);
2081 // Replace WebContentsDelegate with mock version so we can intercept download
2082 // requests.
2083 content::WebContentsDelegate* delegate = guest_web_contents->GetDelegate();
2084 scoped_ptr<MockDownloadWebContentsDelegate>
2085 mock_delegate(new MockDownloadWebContentsDelegate(delegate));
2086 guest_web_contents->SetDelegate(mock_delegate.get());
2088 // Start test.
2089 // 1. Guest requests a download that its embedder denies.
2090 EXPECT_TRUE(content::ExecuteScript(guest_web_contents,
2091 "startDownload('download-link-1')"));
2092 mock_delegate->WaitForCanDownload(false); // Expect to not allow.
2093 mock_delegate->Reset();
2095 // 2. Guest requests a download that its embedder allows.
2096 EXPECT_TRUE(content::ExecuteScript(guest_web_contents,
2097 "startDownload('download-link-2')"));
2098 mock_delegate->WaitForCanDownload(true); // Expect to allow.
2099 mock_delegate->Reset();
2101 // 3. Guest requests a download that its embedder ignores, this implies deny.
2102 EXPECT_TRUE(content::ExecuteScript(guest_web_contents,
2103 "startDownload('download-link-3')"));
2104 mock_delegate->WaitForCanDownload(false); // Expect to not allow.
2107 // This test makes sure loading <webview> does not crash when there is an
2108 // extension which has content script whitelisted/forced.
2109 IN_PROC_BROWSER_TEST_F(WebViewTest, WhitelistedContentScript) {
2110 // Whitelist the extension for running content script we are going to load.
2111 extensions::ExtensionsClient::ScriptingWhitelist whitelist;
2112 const std::string extension_id = "imeongpbjoodlnmlakaldhlcmijmhpbb";
2113 whitelist.push_back(extension_id);
2114 extensions::ExtensionsClient::Get()->SetScriptingWhitelist(whitelist);
2116 // Load the extension.
2117 const extensions::Extension* content_script_whitelisted_extension =
2118 LoadExtension(test_data_dir_.AppendASCII(
2119 "platform_apps/web_view/extension_api/content_script"));
2120 ASSERT_TRUE(content_script_whitelisted_extension);
2121 ASSERT_EQ(extension_id, content_script_whitelisted_extension->id());
2123 // Now load an app with <webview>.
2124 LoadAndLaunchPlatformApp("web_view/content_script_whitelisted",
2125 "TEST_PASSED");
2128 IN_PROC_BROWSER_TEST_F(WebViewTest, SendMessageToExtensionFromGuest) {
2129 // Load the extension as a normal, non-component extension.
2130 const extensions::Extension* extension =
2131 LoadExtension(test_data_dir_.AppendASCII(
2132 "platform_apps/web_view/extension_api/component_extension"));
2133 ASSERT_TRUE(extension);
2135 TestHelper("testNonComponentExtension", "web_view/component_extension",
2136 NEEDS_TEST_SERVER);
2139 IN_PROC_BROWSER_TEST_F(WebViewTest, SendMessageToComponentExtensionFromGuest) {
2140 const extensions::Extension* component_extension =
2141 LoadExtensionAsComponent(test_data_dir_.AppendASCII(
2142 "platform_apps/web_view/extension_api/component_extension"));
2143 ASSERT_TRUE(component_extension);
2145 TestHelper("testComponentExtension", "web_view/component_extension",
2146 NEEDS_TEST_SERVER);
2148 content::WebContents* embedder_web_contents = GetFirstAppWindowWebContents();
2149 ASSERT_TRUE(embedder_web_contents);
2151 // Retrive the guestProcessId and guestRenderFrameRoutingId from the
2152 // extension.
2153 int guest_process_id = content::ChildProcessHost::kInvalidUniqueID;
2154 content::ExecuteScriptAndGetValue(embedder_web_contents->GetMainFrame(),
2155 "window.guestProcessId")
2156 ->GetAsInteger(&guest_process_id);
2157 int guest_render_frame_routing_id = MSG_ROUTING_NONE;
2158 content::ExecuteScriptAndGetValue(embedder_web_contents->GetMainFrame(),
2159 "window.guestRenderFrameRoutingId")
2160 ->GetAsInteger(&guest_render_frame_routing_id);
2162 auto* guest_rfh = content::RenderFrameHost::FromID(
2163 guest_process_id, guest_render_frame_routing_id);
2164 // Verify that the guest related info (guest_process_id and
2165 // guest_render_frame_routing_id) actually points to a WebViewGuest.
2166 ASSERT_TRUE(extensions::WebViewGuest::FromWebContents(
2167 content::WebContents::FromRenderFrameHost(guest_rfh)));
2170 IN_PROC_BROWSER_TEST_F(WebViewTest, SetPropertyOnDocumentReady) {
2171 ASSERT_TRUE(RunPlatformAppTest("platform_apps/web_view/document_ready"))
2172 << message_;
2175 IN_PROC_BROWSER_TEST_F(WebViewTest, SetPropertyOnDocumentInteractive) {
2176 ASSERT_TRUE(RunPlatformAppTest("platform_apps/web_view/document_interactive"))
2177 << message_;
2180 IN_PROC_BROWSER_TEST_F(WebViewSpeechAPITest,
2181 SpeechRecognitionAPI_HasPermissionAllow) {
2182 ASSERT_TRUE(
2183 RunPlatformAppTestWithArg("platform_apps/web_view/speech_recognition_api",
2184 "allowTest"))
2185 << message_;
2188 IN_PROC_BROWSER_TEST_F(WebViewSpeechAPITest,
2189 SpeechRecognitionAPI_HasPermissionDeny) {
2190 ASSERT_TRUE(
2191 RunPlatformAppTestWithArg("platform_apps/web_view/speech_recognition_api",
2192 "denyTest"))
2193 << message_;
2196 IN_PROC_BROWSER_TEST_F(WebViewSpeechAPITest,
2197 SpeechRecognitionAPI_NoPermission) {
2198 ASSERT_TRUE(
2199 RunPlatformAppTestWithArg("platform_apps/web_view/common",
2200 "speech_recognition_api_no_permission"))
2201 << message_;
2204 // Tests overriding user agent.
2205 IN_PROC_BROWSER_TEST_F(WebViewTest, UserAgent) {
2206 ASSERT_TRUE(RunPlatformAppTestWithArg(
2207 "platform_apps/web_view/common", "useragent")) << message_;
2210 IN_PROC_BROWSER_TEST_F(WebViewNewWindowTest, UserAgent_NewWindow) {
2211 ASSERT_TRUE(RunPlatformAppTestWithArg(
2212 "platform_apps/web_view/common",
2213 "useragent_newwindow")) << message_;
2216 IN_PROC_BROWSER_TEST_F(WebViewTest, NoPermission) {
2217 ASSERT_TRUE(RunPlatformAppTest("platform_apps/web_view/nopermission"))
2218 << message_;
2221 IN_PROC_BROWSER_TEST_F(WebViewTest, Dialog_TestAlertDialog) {
2222 TestHelper("testAlertDialog", "web_view/dialog", NO_TEST_SERVER);
2225 IN_PROC_BROWSER_TEST_F(WebViewTest, TestConfirmDialog) {
2226 TestHelper("testConfirmDialog", "web_view/dialog", NO_TEST_SERVER);
2229 IN_PROC_BROWSER_TEST_F(WebViewTest, Dialog_TestConfirmDialogCancel) {
2230 TestHelper("testConfirmDialogCancel", "web_view/dialog", NO_TEST_SERVER);
2233 IN_PROC_BROWSER_TEST_F(WebViewTest, Dialog_TestConfirmDialogDefaultCancel) {
2234 TestHelper("testConfirmDialogDefaultCancel",
2235 "web_view/dialog",
2236 NO_TEST_SERVER);
2239 IN_PROC_BROWSER_TEST_F(WebViewTest, Dialog_TestConfirmDialogDefaultGCCancel) {
2240 TestHelper("testConfirmDialogDefaultGCCancel",
2241 "web_view/dialog",
2242 NO_TEST_SERVER);
2245 IN_PROC_BROWSER_TEST_F(WebViewTest, Dialog_TestPromptDialog) {
2246 TestHelper("testPromptDialog", "web_view/dialog", NO_TEST_SERVER);
2249 IN_PROC_BROWSER_TEST_F(WebViewTest, NoContentSettingsAPI) {
2250 // Load the extension.
2251 const extensions::Extension* content_settings_extension =
2252 LoadExtension(
2253 test_data_dir_.AppendASCII(
2254 "platform_apps/web_view/extension_api/content_settings"));
2255 ASSERT_TRUE(content_settings_extension);
2256 TestHelper("testPostMessageCommChannel", "web_view/shim", NO_TEST_SERVER);
2259 #if defined(ENABLE_PLUGINS)
2260 class WebViewPluginTest : public WebViewTest {
2261 protected:
2262 void SetUpCommandLine(base::CommandLine* command_line) override {
2263 WebViewTest::SetUpCommandLine(command_line);
2264 ASSERT_TRUE(ppapi::RegisterTestPlugin(command_line));
2268 IN_PROC_BROWSER_TEST_F(WebViewPluginTest, TestLoadPluginEvent) {
2269 TestHelper("testPluginLoadPermission", "web_view/shim", NO_TEST_SERVER);
2272 IN_PROC_BROWSER_TEST_F(WebViewPluginTest, TestLoadPluginInternalResource) {
2273 const char kTestMimeType[] = "application/pdf";
2274 const char kTestFileType[] = "pdf";
2275 content::WebPluginInfo plugin_info;
2276 plugin_info.type = content::WebPluginInfo::PLUGIN_TYPE_PEPPER_OUT_OF_PROCESS;
2277 plugin_info.mime_types.push_back(
2278 content::WebPluginMimeType(kTestMimeType, kTestFileType, std::string()));
2279 content::PluginService::GetInstance()->RegisterInternalPlugin(plugin_info,
2280 true);
2282 TestHelper("testPluginLoadInternalResource", "web_view/shim", NO_TEST_SERVER);
2284 #endif // defined(ENABLE_PLUGINS)
2286 class WebViewCaptureTest : public WebViewTest {
2287 public:
2288 WebViewCaptureTest() {}
2289 ~WebViewCaptureTest() override {}
2290 void SetUp() override {
2291 EnablePixelOutput();
2292 WebViewTest::SetUp();
2296 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestZoomAPI) {
2297 TestHelper("testZoomAPI", "web_view/shim", NO_TEST_SERVER);
2300 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestFindAPI) {
2301 TestHelper("testFindAPI", "web_view/shim", NO_TEST_SERVER);
2304 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestFindAPI_findupdate) {
2305 TestHelper("testFindAPI_findupdate", "web_view/shim", NO_TEST_SERVER);
2308 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestLoadDataAPI) {
2309 TestHelper("testLoadDataAPI", "web_view/shim", NEEDS_TEST_SERVER);
2312 // This test verifies that the resize and contentResize events work correctly.
2313 IN_PROC_BROWSER_TEST_F(WebViewSizeTest, Shim_TestResizeEvents) {
2314 TestHelper("testResizeEvents", "web_view/shim", NO_TEST_SERVER);
2317 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestPerOriginZoomMode) {
2318 TestHelper("testPerOriginZoomMode", "web_view/shim", NO_TEST_SERVER);
2321 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestPerViewZoomMode) {
2322 TestHelper("testPerViewZoomMode", "web_view/shim", NO_TEST_SERVER);
2325 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestDisabledZoomMode) {
2326 TestHelper("testDisabledZoomMode", "web_view/shim", NO_TEST_SERVER);
2329 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestZoomBeforeNavigation) {
2330 TestHelper("testZoomBeforeNavigation", "web_view/shim", NO_TEST_SERVER);
2333 // This test verify that the set of rules registries of a webview will be
2334 // removed from RulesRegistryService after the webview is gone.
2335 // http://crbug.com/438327
2336 IN_PROC_BROWSER_TEST_F(
2337 WebViewTest,
2338 DISABLED_Shim_TestRulesRegistryIDAreRemovedAfterWebViewIsGone) {
2339 LoadAppWithGuest("web_view/rules_registry");
2341 content::WebContents* embedder_web_contents = GetEmbedderWebContents();
2342 ASSERT_TRUE(embedder_web_contents);
2343 scoped_ptr<EmbedderWebContentsObserver> observer(
2344 new EmbedderWebContentsObserver(embedder_web_contents));
2346 content::WebContents* guest_web_contents = GetGuestWebContents();
2347 ASSERT_TRUE(guest_web_contents);
2348 extensions::WebViewGuest* guest =
2349 extensions::WebViewGuest::FromWebContents(guest_web_contents);
2350 ASSERT_TRUE(guest);
2352 // Register rule for the guest.
2353 Profile* profile = browser()->profile();
2354 int rules_registry_id =
2355 extensions::WebViewGuest::GetOrGenerateRulesRegistryID(
2356 guest->owner_web_contents()->GetRenderProcessHost()->GetID(),
2357 guest->view_instance_id());
2359 extensions::RulesRegistryService* registry_service =
2360 extensions::RulesRegistryService::Get(profile);
2361 extensions::TestRulesRegistry* rules_registry =
2362 new extensions::TestRulesRegistry(
2363 content::BrowserThread::UI, "ui", rules_registry_id);
2364 registry_service->RegisterRulesRegistry(make_scoped_refptr(rules_registry));
2366 EXPECT_TRUE(registry_service->GetRulesRegistry(
2367 rules_registry_id, "ui").get());
2369 // Kill the embedder's render process, so the webview will go as well.
2370 base::Process process = base::Process::DeprecatedGetProcessFromHandle(
2371 embedder_web_contents->GetRenderProcessHost()->GetHandle());
2372 process.Terminate(0, false);
2373 observer->WaitForEmbedderRenderProcessTerminate();
2375 EXPECT_FALSE(registry_service->GetRulesRegistry(
2376 rules_registry_id, "ui").get());
2379 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_WebViewWebRequestRegistryHasNoCache) {
2380 LoadAppWithGuest("web_view/rules_registry");
2382 content::WebContents* guest_web_contents = GetGuestWebContents();
2383 ASSERT_TRUE(guest_web_contents);
2384 extensions::WebViewGuest* guest =
2385 extensions::WebViewGuest::FromWebContents(guest_web_contents);
2386 ASSERT_TRUE(guest);
2388 Profile* profile = browser()->profile();
2389 extensions::RulesRegistryService* registry_service =
2390 extensions::RulesRegistryService::Get(profile);
2391 int rules_registry_id =
2392 extensions::WebViewGuest::GetOrGenerateRulesRegistryID(
2393 guest->owner_web_contents()->GetRenderProcessHost()->GetID(),
2394 guest->view_instance_id());
2396 // Get an existing registered rule for the guest.
2397 extensions::RulesRegistry* registry =
2398 registry_service->GetRulesRegistry(
2399 rules_registry_id,
2400 extensions::declarative_webrequest_constants::kOnRequest).get();
2402 EXPECT_TRUE(registry);
2403 EXPECT_FALSE(registry->rules_cache_delegate_for_testing());
2406 // This test verifies that webview.contentWindow works inside an iframe.
2407 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestWebViewInsideFrame) {
2408 LoadAppWithGuest("web_view/inside_iframe");
2411 // <webview> screenshot capture fails with ubercomp.
2412 // See http://crbug.com/327035.
2413 IN_PROC_BROWSER_TEST_F(WebViewCaptureTest,
2414 DISABLED_Shim_ScreenshotCapture) {
2415 TestHelper("testScreenshotCapture", "web_view/shim", NO_TEST_SERVER);
2418 // Tests that browser process does not crash when loading plugin inside
2419 // <webview> with content settings set to CONTENT_SETTING_BLOCK.
2420 IN_PROC_BROWSER_TEST_F(WebViewTest, TestPlugin) {
2421 HostContentSettingsMapFactory::GetForProfile(browser()->profile())
2422 ->SetDefaultContentSetting(CONTENT_SETTINGS_TYPE_PLUGINS,
2423 CONTENT_SETTING_BLOCK);
2424 TestHelper("testPlugin", "web_view/shim", NEEDS_TEST_SERVER);
2427 #if defined(OS_WIN)
2428 // Test is disabled on Windows because it times out often.
2429 // http://crbug.com/403325
2430 #define MAYBE_WebViewInBackgroundPage \
2431 DISABLED_WebViewInBackgroundPage
2432 #else
2433 #define MAYBE_WebViewInBackgroundPage WebViewInBackgroundPage
2434 #endif
2435 IN_PROC_BROWSER_TEST_F(WebViewTest, MAYBE_WebViewInBackgroundPage) {
2436 ASSERT_TRUE(RunExtensionTest("platform_apps/web_view/background"))
2437 << message_;
2440 // This test verifies that the allowtransparency attribute properly propagates.
2441 IN_PROC_BROWSER_TEST_F(WebViewTest, AllowTransparencyAndAllowScalingPropagate) {
2442 LoadAppWithGuest("web_view/simple");
2444 ASSERT_TRUE(GetGuestWebContents());
2445 extensions::WebViewGuest* guest =
2446 extensions::WebViewGuest::FromWebContents(GetGuestWebContents());
2447 ASSERT_TRUE(guest->allow_transparency());
2448 ASSERT_TRUE(guest->allow_scaling());
2451 IN_PROC_BROWSER_TEST_F(WebViewCommonTest, BasicPostMessage) {
2452 ASSERT_TRUE(StartEmbeddedTestServer()); // For serving guest pages.
2453 ASSERT_TRUE(RunPlatformAppTest("platform_apps/web_view/post_message/basic"))
2454 << message_;
2457 // Tests that webviews do get garbage collected.
2458 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestGarbageCollect) {
2459 TestHelper("testGarbageCollect", "web_view/shim", NO_TEST_SERVER);
2460 GetGuestViewManager()->WaitForSingleViewGarbageCollected();
2463 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestCloseNewWindowCleanup) {
2464 TestHelper("testCloseNewWindowCleanup", "web_view/shim", NEEDS_TEST_SERVER);
2465 auto gvm = GetGuestViewManager();
2466 gvm->WaitForLastGuestDeleted();
2467 ASSERT_EQ(gvm->num_embedder_processes_destroyed(), 0);
2470 // Ensure that focusing a WebView while it is already focused does not blur the
2471 // guest content.
2472 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestFocusWhileFocused) {
2473 TestHelper("testFocusWhileFocused", "web_view/shim", NO_TEST_SERVER);
2476 IN_PROC_BROWSER_TEST_F(WebViewTest, NestedGuestContainerBounds) {
2477 TestHelper("testPDFInWebview", "web_view/shim", NO_TEST_SERVER);
2479 std::vector<content::WebContents*> guest_web_contents_list;
2480 GetGuestViewManager()->WaitForNumGuestsCreated(2u);
2481 GetGuestViewManager()->GetGuestWebContentsList(&guest_web_contents_list);
2482 ASSERT_EQ(2u, guest_web_contents_list.size());
2484 content::WebContents* web_view_contents = guest_web_contents_list[0];
2485 content::WebContents* mime_handler_view_contents = guest_web_contents_list[1];
2487 // Make sure we've completed loading |mime_handler_view_guest|.
2488 bool load_success = pdf_extension_test_util::EnsurePDFHasLoaded(
2489 web_view_contents);
2490 EXPECT_TRUE(load_success);
2492 gfx::Rect web_view_container_bounds = web_view_contents->GetContainerBounds();
2493 gfx::Rect mime_handler_view_container_bounds =
2494 mime_handler_view_contents->GetContainerBounds();
2495 EXPECT_EQ(web_view_container_bounds.origin(),
2496 mime_handler_view_container_bounds.origin());
2499 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestMailtoLink) {
2500 TestHelper("testMailtoLink", "web_view/shim", NEEDS_TEST_SERVER);
2503 // Tests that a renderer navigation from an unattached guest that results in a
2504 // server redirect works properly.
2505 IN_PROC_BROWSER_TEST_F(WebViewTest,
2506 Shim_TestRendererNavigationRedirectWhileUnattached) {
2507 TestHelper("testRendererNavigationRedirectWhileUnattached",
2508 "web_view/shim", NEEDS_TEST_SERVER);
2511 // Tests that a WebView accessible resource can actually be loaded from a
2512 // webpage in a WebView.
2513 IN_PROC_BROWSER_TEST_F(WebViewTest, LoadWebviewAccessibleResource) {
2514 TestHelper("testLoadWebviewAccessibleResource",
2515 "web_view/load_webview_accessible_resource", NEEDS_TEST_SERVER);
2518 #if defined(USE_AURA)
2519 // TODO(wjmaclean): when WebViewTest is re-enabled on the site-isolation
2520 // bots, then re-enable this test class as well.
2521 // https://crbug.com/503751
2522 class WebViewFocusTest : public WebViewTest {
2523 public:
2524 ~WebViewFocusTest() override {}
2526 void SetUpCommandLine(base::CommandLine* command_line) override {
2527 WebViewTest::SetUpCommandLine(command_line);
2529 command_line->AppendSwitchASCII(switches::kTouchEvents,
2530 switches::kTouchEventsEnabled);
2533 void ForceCompositorFrame() {
2534 if (!frame_watcher_) {
2535 frame_watcher_ = new content::FrameWatcher();
2536 frame_watcher_->AttachTo(GetEmbedderWebContents());
2539 while (!RequestFrame(GetEmbedderWebContents())) {
2540 // RequestFrame failed because we were waiting on an ack ... wait a short
2541 // time and retry.
2542 base::RunLoop run_loop;
2543 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
2544 FROM_HERE, run_loop.QuitClosure(),
2545 base::TimeDelta::FromMilliseconds(10));
2546 run_loop.Run();
2548 frame_watcher_->WaitFrames(1);
2551 private:
2552 scoped_refptr<content::FrameWatcher> frame_watcher_;
2555 class FocusWaiter : public views::FocusChangeListener {
2556 public:
2557 explicit FocusWaiter(views::View* view_to_wait_for)
2558 : view_to_wait_for_(view_to_wait_for) {
2559 view_to_wait_for_->GetFocusManager()->AddFocusChangeListener(this);
2561 ~FocusWaiter() override {
2562 view_to_wait_for_->GetFocusManager()->RemoveFocusChangeListener(this);
2565 void Wait() {
2566 if (view_to_wait_for_->HasFocus())
2567 return;
2569 base::MessageLoop::current()->Run();
2572 // FocusChangeListener implementation.
2573 void OnWillChangeFocus(views::View* focused_before,
2574 views::View* focused_now) override {}
2575 void OnDidChangeFocus(views::View* focused_before,
2576 views::View* focused_now) override {
2577 if (view_to_wait_for_ == focused_now)
2578 base::MessageLoop::current()->QuitWhenIdle();
2581 private:
2582 views::View* view_to_wait_for_;
2584 DISALLOW_COPY_AND_ASSIGN(FocusWaiter);
2587 // The following test verifies that a views::WebView hosting an embedder
2588 // gains focus on touchstart.
2589 IN_PROC_BROWSER_TEST_F(WebViewFocusTest, TouchFocusesEmbedder) {
2590 LoadAppWithGuest("web_view/accept_touch_events");
2592 content::WebContents* web_contents = GetEmbedderWebContents();
2593 content::RenderViewHost* embedder_rvh = web_contents->GetRenderViewHost();
2595 bool embedder_has_touch_handler =
2596 content::RenderViewHostTester::HasTouchEventHandler(embedder_rvh);
2597 EXPECT_FALSE(embedder_has_touch_handler);
2599 SendMessageToGuestAndWait("install-touch-handler", "installed-touch-handler");
2601 // Note that we need to wait for the installed/registered touch handler to
2602 // appear in browser process before querying |embedder_rvh|.
2603 // In practice, since we do a roundrtip from browser process to guest and
2604 // back, this is sufficient.
2605 embedder_has_touch_handler =
2606 content::RenderViewHostTester::HasTouchEventHandler(embedder_rvh);
2607 EXPECT_TRUE(embedder_has_touch_handler);
2609 extensions::AppWindow* app_window = GetFirstAppWindowForBrowser(browser());
2610 aura::Window* window = app_window->GetNativeWindow();
2611 EXPECT_TRUE(app_window);
2612 EXPECT_TRUE(window);
2613 views::Widget* widget = views::Widget::GetWidgetForNativeView(window);
2614 EXPECT_TRUE(widget->GetRootView());
2615 // We only expect a single views::webview in the view hierarchy.
2616 views::View* aura_webview = FindWebView(widget->GetRootView());
2617 ASSERT_TRUE(aura_webview);
2618 gfx::Rect bounds(aura_webview->bounds());
2619 EXPECT_TRUE(aura_webview->IsFocusable());
2621 views::View* other_focusable_view = new views::View();
2622 other_focusable_view->SetBounds(bounds.x() + bounds.width(), bounds.y(), 100,
2623 100);
2624 other_focusable_view->SetFocusable(true);
2625 aura_webview->parent()->AddChildView(other_focusable_view);
2626 other_focusable_view->SetPosition(gfx::Point(bounds.x() + bounds.width(), 0));
2628 // Sync changes to compositor.
2629 ForceCompositorFrame();
2631 aura_webview->RequestFocus();
2632 // Verify that other_focusable_view can steal focus from aura_webview.
2633 EXPECT_TRUE(aura_webview->HasFocus());
2634 other_focusable_view->RequestFocus();
2635 EXPECT_TRUE(other_focusable_view->HasFocus());
2636 EXPECT_FALSE(aura_webview->HasFocus());
2638 // Compute location of guest within embedder so we can more accurately
2639 // target our touch event.
2640 gfx::Rect guest_rect = GetGuestWebContents()->GetContainerBounds();
2641 gfx::Point embedder_origin =
2642 GetEmbedderWebContents()->GetContainerBounds().origin();
2643 guest_rect.Offset(-embedder_origin.x(), -embedder_origin.y());
2645 // Generate and send synthetic touch event.
2646 FocusWaiter waiter(aura_webview);
2647 content::SimulateTouchPressAt(GetEmbedderWebContents(),
2648 guest_rect.CenterPoint());
2650 // Wait for the TouchStart to propagate and restore focus. Test times out
2651 // on failure.
2652 waiter.Wait();
2654 #endif
2656 #if defined(ENABLE_TASK_MANAGER)
2658 namespace {
2660 base::string16 GetExpectedPrefix(content::WebContents* web_contents) {
2661 DCHECK(web_contents);
2662 guest_view::GuestViewBase* guest =
2663 guest_view::GuestViewBase::FromWebContents(web_contents);
2664 DCHECK(guest);
2666 return l10n_util::GetStringFUTF16(guest->GetTaskPrefix(), base::string16());
2669 const std::vector<task_management::WebContentsTag*>& GetTrackedTags() {
2670 return task_management::WebContentsTagsManager::GetInstance()->
2671 tracked_tags();
2674 } // namespace
2676 // Tests that the pre-existing WebViews are provided to the task manager.
2677 IN_PROC_BROWSER_TEST_F(WebViewTest, TaskManagementPreExistingWebViews) {
2678 ASSERT_TRUE(StartEmbeddedTestServer());
2680 // Browser tests start with a single tab.
2681 EXPECT_EQ(1U, GetTrackedTags().size());
2683 content::WebContents* guest_contents =
2684 LoadGuest("/extensions/platform_apps/web_view/task_manager/guest.html",
2685 "web_view/task_manager");
2687 task_management::MockWebContentsTaskManager task_manager;
2688 task_manager.StartObserving();
2690 // The pre-existing tab and guest tasks are provided.
2691 // 4 tasks expected in the following order:
2692 // Tab: about:blank,
2693 // Background Page: <webview> task manager test,
2694 // App: <webview> task manager test,
2695 // Webview: WebViewed test content.
2696 EXPECT_EQ(4U, task_manager.tasks().size());
2698 const task_management::Task* task = task_manager.tasks().back();
2699 EXPECT_EQ(task_management::Task::GUEST, task->GetType());
2700 const base::string16 title = task->title();
2701 const base::string16 expected_prefix = GetExpectedPrefix(guest_contents);
2702 EXPECT_TRUE(base::StartsWith(title,
2703 expected_prefix,
2704 base::CompareCase::INSENSITIVE_ASCII));
2707 // Tests that the post-existing WebViews are provided to the task manager.
2708 IN_PROC_BROWSER_TEST_F(WebViewTest, TaskManagementPostExistingWebViews) {
2709 ASSERT_TRUE(StartEmbeddedTestServer());
2711 // Browser tests start with a single tab.
2712 EXPECT_EQ(1U, GetTrackedTags().size());
2714 task_management::MockWebContentsTaskManager task_manager;
2715 task_manager.StartObserving();
2717 // Only the "about:blank" tab shows at the moment.
2718 EXPECT_EQ(1U, task_manager.tasks().size());
2719 const task_management::Task* about_blank_task = task_manager.tasks().back();
2720 EXPECT_EQ(task_management::Task::RENDERER, about_blank_task->GetType());
2721 EXPECT_EQ(base::UTF8ToUTF16("Tab: about:blank"), about_blank_task->title());
2723 // Now load a guest web view.
2724 content::WebContents* guest_contents =
2725 LoadGuest("/extensions/platform_apps/web_view/task_manager/guest.html",
2726 "web_view/task_manager");
2727 // 4 tasks expected in the following order:
2728 // Tab: about:blank,
2729 // Background Page: <webview> task manager test,
2730 // App: <webview> task manager test,
2731 // Webview: WebViewed test content.
2732 EXPECT_EQ(4U, task_manager.tasks().size());
2734 const task_management::Task* task = task_manager.tasks().back();
2735 EXPECT_EQ(task_management::Task::GUEST, task->GetType());
2736 const base::string16 title = task->title();
2737 const base::string16 expected_prefix = GetExpectedPrefix(guest_contents);
2738 EXPECT_TRUE(base::StartsWith(title,
2739 expected_prefix,
2740 base::CompareCase::INSENSITIVE_ASCII));
2743 #endif // defined(ENABLE_TASK_MANAGER)