1 // Copyright (c) 2012 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.
7 #include "base/command_line.h"
8 #include "base/compiler_specific.h"
9 #include "base/strings/string_number_conversions.h"
10 #include "base/strings/stringprintf.h"
11 #include "base/strings/utf_string_conversions.h"
12 #include "base/test/simple_test_clock.h"
13 #include "base/time/clock.h"
14 #include "chrome/browser/chrome_notification_types.h"
15 #include "chrome/browser/content_settings/tab_specific_content_settings.h"
16 #include "chrome/browser/infobars/infobar_service.h"
17 #include "chrome/browser/profiles/profile.h"
18 #include "chrome/browser/ui/browser.h"
19 #include "chrome/browser/ui/browser_commands.h"
20 #include "chrome/browser/ui/tabs/tab_strip_model.h"
21 #include "chrome/browser/ui/website_settings/mock_permission_bubble_view.h"
22 #include "chrome/browser/ui/website_settings/permission_bubble_manager.h"
23 #include "chrome/common/chrome_paths.h"
24 #include "chrome/common/chrome_switches.h"
25 #include "chrome/test/base/in_process_browser_test.h"
26 #include "chrome/test/base/ui_test_utils.h"
27 #include "components/content_settings/core/browser/content_settings_usages_state.h"
28 #include "components/content_settings/core/browser/host_content_settings_map.h"
29 #include "components/content_settings/core/common/content_settings_pattern.h"
30 #include "components/infobars/core/confirm_infobar_delegate.h"
31 #include "components/infobars/core/infobar.h"
32 #include "content/public/browser/dom_operation_notification_details.h"
33 #include "content/public/browser/navigation_controller.h"
34 #include "content/public/browser/notification_details.h"
35 #include "content/public/browser/notification_service.h"
36 #include "content/public/browser/render_frame_host.h"
37 #include "content/public/browser/web_contents.h"
38 #include "content/public/test/browser_test_utils.h"
39 #include "net/base/net_util.h"
40 #include "net/test/embedded_test_server/embedded_test_server.h"
42 using content::DomOperationNotificationDetails
;
43 using content::NavigationController
;
44 using content::WebContents
;
48 // IFrameLoader ---------------------------------------------------------------
50 // Used to block until an iframe is loaded via a javascript call.
51 // Note: NavigateToURLBlockUntilNavigationsComplete doesn't seem to work for
52 // multiple embedded iframes, as notifications seem to be 'batched'. Instead, we
53 // load and wait one single frame here by calling a javascript function.
54 class IFrameLoader
: public content::NotificationObserver
{
56 IFrameLoader(Browser
* browser
, int iframe_id
, const GURL
& url
);
57 ~IFrameLoader() override
;
59 // content::NotificationObserver:
60 void Observe(int type
,
61 const content::NotificationSource
& source
,
62 const content::NotificationDetails
& details
) override
;
64 const GURL
& iframe_url() const { return iframe_url_
; }
67 content::NotificationRegistrar registrar_
;
69 // If true the navigation has completed.
70 bool navigation_completed_
;
72 // If true the javascript call has completed.
73 bool javascript_completed_
;
75 std::string javascript_response_
;
77 // The URL for the iframe we just loaded.
80 DISALLOW_COPY_AND_ASSIGN(IFrameLoader
);
83 IFrameLoader::IFrameLoader(Browser
* browser
, int iframe_id
, const GURL
& url
)
84 : navigation_completed_(false),
85 javascript_completed_(false) {
86 WebContents
* web_contents
=
87 browser
->tab_strip_model()->GetActiveWebContents();
88 NavigationController
* controller
= &web_contents
->GetController();
89 registrar_
.Add(this, content::NOTIFICATION_LOAD_STOP
,
90 content::Source
<NavigationController
>(controller
));
91 registrar_
.Add(this, content::NOTIFICATION_DOM_OPERATION_RESPONSE
,
92 content::NotificationService::AllSources());
93 std::string
script(base::StringPrintf(
94 "window.domAutomationController.setAutomationId(0);"
95 "window.domAutomationController.send(addIFrame(%d, \"%s\"));",
96 iframe_id
, url
.spec().c_str()));
97 web_contents
->GetMainFrame()->ExecuteJavaScript(base::UTF8ToUTF16(script
));
98 content::RunMessageLoop();
100 EXPECT_EQ(base::StringPrintf("\"%d\"", iframe_id
), javascript_response_
);
101 registrar_
.RemoveAll();
102 // Now that we loaded the iframe, let's fetch its src.
103 script
= base::StringPrintf(
104 "window.domAutomationController.send(getIFrameSrc(%d))", iframe_id
);
105 std::string iframe_src
;
106 EXPECT_TRUE(content::ExecuteScriptAndExtractString(web_contents
, script
,
108 iframe_url_
= GURL(iframe_src
);
111 IFrameLoader::~IFrameLoader() {
114 void IFrameLoader::Observe(int type
,
115 const content::NotificationSource
& source
,
116 const content::NotificationDetails
& details
) {
117 if (type
== content::NOTIFICATION_LOAD_STOP
) {
118 navigation_completed_
= true;
119 } else if (type
== content::NOTIFICATION_DOM_OPERATION_RESPONSE
) {
120 content::Details
<DomOperationNotificationDetails
> dom_op_details(details
);
121 javascript_response_
= dom_op_details
->json
;
122 javascript_completed_
= true;
124 if (javascript_completed_
&& navigation_completed_
)
125 base::MessageLoopForUI::current()->Quit();
128 // GeolocationNotificationObserver --------------------------------------------
130 class GeolocationNotificationObserver
: public content::NotificationObserver
{
132 // If |wait_for_prompt| is true, AddWatchAndWaitForNotification will block
133 // until the prompt has been displayed; otherwise it will block until the
134 // navigation is completed. Does not take ownership of |view|.
135 GeolocationNotificationObserver(
136 bool wait_for_prompt
, MockPermissionBubbleView
* view
);
137 ~GeolocationNotificationObserver() override
;
139 // content::NotificationObserver:
140 void Observe(int type
,
141 const content::NotificationSource
& source
,
142 const content::NotificationDetails
& details
) override
;
144 // Note: also runs the 'geoStart' method in the test JS script.
145 void AddWatchAndWaitForNotification(
146 content::RenderFrameHost
* render_frame_host
);
148 bool has_infobar() const { return !!infobar_
; }
149 infobars::InfoBar
* infobar() { return infobar_
; }
152 content::NotificationRegistrar registrar_
;
153 bool wait_for_prompt_
;
154 infobars::InfoBar
* infobar_
;
155 bool navigation_started_
;
156 bool navigation_completed_
;
157 std::string javascript_response_
;
158 MockPermissionBubbleView
* mock_view_
;
160 DISALLOW_COPY_AND_ASSIGN(GeolocationNotificationObserver
);
163 GeolocationNotificationObserver::GeolocationNotificationObserver(
164 bool wait_for_prompt
,
165 MockPermissionBubbleView
* view
)
166 : wait_for_prompt_(wait_for_prompt
),
168 navigation_started_(false),
169 navigation_completed_(false),
171 registrar_
.Add(this, content::NOTIFICATION_DOM_OPERATION_RESPONSE
,
172 content::NotificationService::AllSources());
173 if (wait_for_prompt
&& !PermissionBubbleManager::Enabled()) {
174 registrar_
.Add(this, chrome::NOTIFICATION_TAB_CONTENTS_INFOBAR_ADDED
,
175 content::NotificationService::AllSources());
176 } else if (!wait_for_prompt
) {
177 registrar_
.Add(this, content::NOTIFICATION_NAV_ENTRY_COMMITTED
,
178 content::NotificationService::AllSources());
179 registrar_
.Add(this, content::NOTIFICATION_LOAD_START
,
180 content::NotificationService::AllSources());
181 registrar_
.Add(this, content::NOTIFICATION_LOAD_STOP
,
182 content::NotificationService::AllSources());
184 if (PermissionBubbleManager::Enabled())
185 mock_view_
->SetBrowserTest(true);
188 GeolocationNotificationObserver::~GeolocationNotificationObserver() {
191 void GeolocationNotificationObserver::Observe(
193 const content::NotificationSource
& source
,
194 const content::NotificationDetails
& details
) {
195 if (type
== chrome::NOTIFICATION_TAB_CONTENTS_INFOBAR_ADDED
) {
196 infobar_
= content::Details
<infobars::InfoBar::AddedDetails
>(details
).ptr();
197 ASSERT_FALSE(infobar_
->delegate()->GetIcon().IsEmpty());
198 ASSERT_TRUE(infobar_
->delegate()->AsConfirmInfoBarDelegate());
199 } else if (type
== content::NOTIFICATION_DOM_OPERATION_RESPONSE
) {
200 content::Details
<DomOperationNotificationDetails
> dom_op_details(details
);
201 javascript_response_
= dom_op_details
->json
;
202 LOG(WARNING
) << "javascript_response " << javascript_response_
;
203 if (wait_for_prompt_
&& PermissionBubbleManager::Enabled())
204 base::MessageLoopForUI::current()->Quit();
205 } else if ((type
== content::NOTIFICATION_NAV_ENTRY_COMMITTED
) ||
206 (type
== content::NOTIFICATION_LOAD_START
)) {
207 navigation_started_
= true;
208 } else if ((type
== content::NOTIFICATION_LOAD_STOP
) && navigation_started_
) {
209 navigation_started_
= false;
210 navigation_completed_
= true;
213 // We're either waiting for just the infobar, or for both a javascript
214 // prompt and response.
215 if ((wait_for_prompt_
&& infobar_
&& !PermissionBubbleManager::Enabled()) ||
216 (navigation_completed_
&& !javascript_response_
.empty()))
217 base::MessageLoopForUI::current()->Quit();
220 void GeolocationNotificationObserver::AddWatchAndWaitForNotification(
221 content::RenderFrameHost
* render_frame_host
) {
222 if (!PermissionBubbleManager::Enabled()) {
223 LOG(WARNING
) << "will add geolocation watch";
225 "window.domAutomationController.setAutomationId(0);"
226 "window.domAutomationController.send(geoStart());");
227 render_frame_host
->ExecuteJavaScript(base::UTF8ToUTF16(script
));
228 content::RunMessageLoop();
229 registrar_
.RemoveAll();
230 LOG(WARNING
) << "got geolocation watch" << javascript_response_
;
231 EXPECT_NE("\"0\"", javascript_response_
);
233 wait_for_prompt_
? (infobar_
!= nullptr) : navigation_completed_
);
235 LOG(WARNING
) << "will add geolocation watch for bubble";
237 "window.domAutomationController.setAutomationId(0);"
238 "window.domAutomationController.send(geoStart());");
239 render_frame_host
->ExecuteJavaScript(base::UTF8ToUTF16(script
));
240 content::RunMessageLoop();
241 while (wait_for_prompt_
&& !mock_view_
->IsVisible())
242 content::RunMessageLoop();
249 // GeolocationBrowserTest -----------------------------------------------------
251 // This is a browser test for Geolocation.
252 // It exercises various integration points from javascript <-> browser:
253 // 1. Prompt is displayed when a geolocation is requested from an unauthorized
255 // 2. Denying the request triggers the correct error callback.
256 // 3. Allowing the request does not trigger an error, and allow a geoposition to
257 // be passed to javascript.
258 // 4. Permissions persisted in disk are respected.
259 // 5. Incognito profiles don't use saved permissions.
260 class GeolocationBrowserTest
: public InProcessBrowserTest
,
261 public testing::WithParamInterface
<bool> {
263 enum InitializationOptions
{
265 INITIALIZATION_OFFTHERECORD
,
266 INITIALIZATION_NEWTAB
,
267 INITIALIZATION_IFRAMES
,
270 GeolocationBrowserTest();
271 ~GeolocationBrowserTest() override
;
273 // InProcessBrowserTest:
274 void SetUpOnMainThread() override
;
275 void TearDownInProcessBrowserTestFixture() override
;
277 Browser
* current_browser() { return current_browser_
; }
278 void set_html_for_tests(const std::string
& html_for_tests
) {
279 html_for_tests_
= html_for_tests
;
281 content::RenderFrameHost
* frame_host() const { return render_frame_host_
; }
282 const GURL
& current_url() const { return current_url_
; }
283 const GURL
& iframe_url(size_t i
) const { return iframe_urls_
[i
]; }
284 double fake_latitude() const { return fake_latitude_
; }
285 double fake_longitude() const { return fake_longitude_
; }
287 // Initializes the test server and navigates to the initial url.
288 bool Initialize(InitializationOptions options
) WARN_UNUSED_RESULT
;
290 // Loads the specified number of iframes.
291 void LoadIFrames(int number_iframes
);
293 // Specifies which frame is to be used for JavaScript calls.
294 void SetFrameHost(const std::string
& frame_name
);
296 // Start watching for geolocation notifications. If |wait_for_prompt| is
297 // true, wait for the prompt (infobar or bubble) to be displayed. Otherwise
298 // wait for a javascript response.
299 void AddGeolocationWatch(bool wait_for_prompt
);
301 // Checks that no errors have been received in javascript, and checks that the
302 // position most recently received in javascript matches |latitude| and
304 void CheckGeoposition(double latitude
, double longitude
);
306 // For |requesting_url| if |allowed| is true accept the prompt. Otherwise
308 void SetPromptResponse(const GURL
& requesting_url
, bool allowed
);
310 // Executes |function| in |render_frame_host| and checks that the return value
311 // matches |expected|.
312 void CheckStringValueFromJavascriptForFrame(
313 const std::string
& expected
,
314 const std::string
& function
,
315 content::RenderFrameHost
* render_frame_host
);
317 // Executes |function| and checks that the return value matches |expected|.
318 void CheckStringValueFromJavascript(const std::string
& expected
,
319 const std::string
& function
);
321 // Sets a new position and sends a notification with the new position.
322 void NotifyGeoposition(double latitude
, double longitude
);
324 // Convenience method to look up the number of queued permission bubbles.
325 int GetBubblesQueueSize(PermissionBubbleManager
* mgr
);
328 infobars::InfoBar
* infobar_
;
329 Browser
* current_browser_
;
330 // path element of a URL referencing the html content for this test.
331 std::string html_for_tests_
;
332 // This member defines the frame where the JavaScript calls will run.
333 content::RenderFrameHost
* render_frame_host_
;
334 // The current url for the top level page.
336 // If not empty, the GURLs for the iframes loaded by LoadIFrames().
337 std::vector
<GURL
> iframe_urls_
;
338 double fake_latitude_
;
339 double fake_longitude_
;
340 MockPermissionBubbleView mock_bubble_view_
;
342 DISALLOW_COPY_AND_ASSIGN(GeolocationBrowserTest
);
345 GeolocationBrowserTest::GeolocationBrowserTest()
347 current_browser_(nullptr),
348 html_for_tests_("/geolocation/simple.html"),
349 render_frame_host_(nullptr),
350 fake_latitude_(1.23),
351 fake_longitude_(4.56) {
354 GeolocationBrowserTest::~GeolocationBrowserTest() {
357 void GeolocationBrowserTest::SetUpOnMainThread() {
358 ui_test_utils::OverrideGeolocation(fake_latitude_
, fake_longitude_
);
359 #if !defined(OS_ANDROID)
361 base::CommandLine::ForCurrentProcess()->AppendSwitch(
362 switches::kEnablePermissionsBubbles
);
363 EXPECT_TRUE(PermissionBubbleManager::Enabled());
365 base::CommandLine::ForCurrentProcess()->AppendSwitch(
366 switches::kDisablePermissionsBubbles
);
367 EXPECT_FALSE(PermissionBubbleManager::Enabled());
372 void GeolocationBrowserTest::TearDownInProcessBrowserTestFixture() {
373 LOG(WARNING
) << "TearDownInProcessBrowserTestFixture. Test Finished.";
376 bool GeolocationBrowserTest::Initialize(InitializationOptions options
) {
377 if (!embedded_test_server()->Started() &&
378 !embedded_test_server()->InitializeAndWaitUntilReady()) {
379 ADD_FAILURE() << "Test server failed to start.";
383 current_url_
= embedded_test_server()->GetURL(html_for_tests_
);
384 LOG(WARNING
) << "before navigate";
385 if (options
== INITIALIZATION_OFFTHERECORD
) {
386 current_browser_
= ui_test_utils::OpenURLOffTheRecord(
387 browser()->profile(), current_url_
);
389 current_browser_
= browser();
390 if (options
== INITIALIZATION_NEWTAB
)
391 chrome::NewTab(current_browser_
);
393 WebContents
* web_contents
=
394 current_browser_
->tab_strip_model()->GetActiveWebContents();
395 PermissionBubbleManager::FromWebContents(web_contents
)->SetView(
397 if (options
!= INITIALIZATION_OFFTHERECORD
)
398 ui_test_utils::NavigateToURL(current_browser_
, current_url_
);
399 LOG(WARNING
) << "after navigate";
401 EXPECT_TRUE(current_browser_
);
402 return !!current_browser_
;
405 void GeolocationBrowserTest::LoadIFrames(int number_iframes
) {
406 // Limit to 3 iframes.
407 DCHECK_LT(0, number_iframes
);
408 DCHECK_LE(number_iframes
, 3);
409 iframe_urls_
.resize(number_iframes
);
410 for (int i
= 0; i
< number_iframes
; ++i
) {
411 IFrameLoader
loader(current_browser_
, i
, GURL());
412 iframe_urls_
[i
] = loader
.iframe_url();
416 void GeolocationBrowserTest::SetFrameHost(const std::string
& frame_name
) {
417 WebContents
* web_contents
=
418 current_browser_
->tab_strip_model()->GetActiveWebContents();
419 render_frame_host_
= nullptr;
421 if (frame_name
.empty()) {
422 render_frame_host_
= web_contents
->GetMainFrame();
424 render_frame_host_
= content::FrameMatchingPredicate(
425 web_contents
, base::Bind(&content::FrameMatchesName
, frame_name
));
427 DCHECK(render_frame_host_
);
430 void GeolocationBrowserTest::AddGeolocationWatch(bool wait_for_prompt
) {
431 GeolocationNotificationObserver
notification_observer(
432 wait_for_prompt
, &mock_bubble_view_
);
433 notification_observer
.AddWatchAndWaitForNotification(render_frame_host_
);
434 if (wait_for_prompt
&& !PermissionBubbleManager::Enabled()) {
435 EXPECT_TRUE(notification_observer
.has_infobar());
436 infobar_
= notification_observer
.infobar();
440 void GeolocationBrowserTest::CheckGeoposition(double latitude
,
442 // Checks we have no error.
443 CheckStringValueFromJavascript("0", "geoGetLastError()");
444 CheckStringValueFromJavascript(base::DoubleToString(latitude
),
445 "geoGetLastPositionLatitude()");
446 CheckStringValueFromJavascript(base::DoubleToString(longitude
),
447 "geoGetLastPositionLongitude()");
450 void GeolocationBrowserTest::SetPromptResponse(const GURL
& requesting_url
,
452 WebContents
* web_contents
=
453 current_browser_
->tab_strip_model()->GetActiveWebContents();
454 TabSpecificContentSettings
* content_settings
=
455 TabSpecificContentSettings::FromWebContents(web_contents
);
456 const ContentSettingsUsagesState
& usages_state
=
457 content_settings
->geolocation_usages_state();
458 size_t state_map_size
= usages_state
.state_map().size();
460 if (PermissionBubbleManager::Enabled()) {
462 mock_bubble_view_
.Accept();
464 mock_bubble_view_
.Deny();
466 EXPECT_GT(usages_state
.state_map().size(), state_map_size
);
467 GURL
requesting_origin(requesting_url
.GetOrigin());
468 EXPECT_EQ(1U, usages_state
.state_map().count(requesting_origin
));
469 ContentSetting expected_setting
=
470 allowed
? CONTENT_SETTING_ALLOW
: CONTENT_SETTING_BLOCK
;
471 EXPECT_EQ(expected_setting
,
472 usages_state
.state_map().find(requesting_origin
)->second
);
473 content::RunAllPendingInMessageLoop();
474 LOG(WARNING
) << "set permission bubble response";
476 ASSERT_TRUE(infobar_
);
477 LOG(WARNING
) << "will set infobar response";
479 content::WindowedNotificationObserver
observer(
480 content::NOTIFICATION_LOAD_STOP
,
481 content::Source
<NavigationController
>(
482 &web_contents
->GetController()));
484 infobar_
->delegate()->AsConfirmInfoBarDelegate()->Accept();
486 infobar_
->delegate()->AsConfirmInfoBarDelegate()->Cancel();
490 InfoBarService
* infobar_service
=
491 InfoBarService::FromWebContents(web_contents
);
492 infobar_service
->RemoveInfoBar(infobar_
);
493 LOG(WARNING
) << "infobar response set";
495 EXPECT_GT(usages_state
.state_map().size(), state_map_size
);
496 GURL
requesting_origin(requesting_url
.GetOrigin());
497 EXPECT_EQ(1U, usages_state
.state_map().count(requesting_origin
));
498 ContentSetting expected_setting
=
499 allowed
? CONTENT_SETTING_ALLOW
: CONTENT_SETTING_BLOCK
;
500 EXPECT_EQ(expected_setting
,
501 usages_state
.state_map().find(requesting_origin
)->second
);
505 void GeolocationBrowserTest::CheckStringValueFromJavascriptForFrame(
506 const std::string
& expected
,
507 const std::string
& function
,
508 content::RenderFrameHost
* render_frame_host
) {
509 std::string
script(base::StringPrintf(
510 "window.domAutomationController.send(%s)", function
.c_str()));
512 ASSERT_TRUE(content::ExecuteScriptAndExtractString(
513 render_frame_host
, script
, &result
));
514 EXPECT_EQ(expected
, result
);
517 void GeolocationBrowserTest::CheckStringValueFromJavascript(
518 const std::string
& expected
,
519 const std::string
& function
) {
520 CheckStringValueFromJavascriptForFrame(
521 expected
, function
, render_frame_host_
);
524 void GeolocationBrowserTest::NotifyGeoposition(double latitude
,
526 fake_latitude_
= latitude
;
527 fake_longitude_
= longitude
;
528 ui_test_utils::OverrideGeolocation(latitude
, longitude
);
529 LOG(WARNING
) << "MockLocationProvider listeners updated";
532 int GeolocationBrowserTest::GetBubblesQueueSize(PermissionBubbleManager
* mgr
) {
533 return static_cast<int>(mgr
->requests_
.size());
536 // Tests ----------------------------------------------------------------------
538 IN_PROC_BROWSER_TEST_P(GeolocationBrowserTest
, DisplaysPrompt
) {
539 ASSERT_TRUE(Initialize(INITIALIZATION_NONE
));
541 AddGeolocationWatch(true);
544 IN_PROC_BROWSER_TEST_P(GeolocationBrowserTest
, Geoposition
) {
545 ASSERT_TRUE(Initialize(INITIALIZATION_NONE
));
547 AddGeolocationWatch(true);
548 SetPromptResponse(current_url(), true);
549 CheckGeoposition(fake_latitude(), fake_longitude());
552 IN_PROC_BROWSER_TEST_P(GeolocationBrowserTest
,
553 ErrorOnPermissionDenied
) {
554 ASSERT_TRUE(Initialize(INITIALIZATION_NONE
));
556 AddGeolocationWatch(true);
557 // Prompt was displayed, deny access and check for error code.
558 SetPromptResponse(current_url(), false);
559 CheckStringValueFromJavascript("1", "geoGetLastError()");
562 // See http://crbug.com/308358
563 IN_PROC_BROWSER_TEST_P(GeolocationBrowserTest
, DISABLED_NoPromptForSecondTab
) {
564 ASSERT_TRUE(Initialize(INITIALIZATION_NONE
));
566 AddGeolocationWatch(true);
567 SetPromptResponse(current_url(), true);
568 // Disables further prompts from this tab.
569 CheckStringValueFromJavascript("0", "geoSetMaxNavigateCount(0)");
571 // Checks infobar will not be created in a second tab.
572 ASSERT_TRUE(Initialize(INITIALIZATION_NEWTAB
));
574 AddGeolocationWatch(false);
575 CheckGeoposition(fake_latitude(), fake_longitude());
578 IN_PROC_BROWSER_TEST_P(GeolocationBrowserTest
, NoPromptForDeniedOrigin
) {
579 ASSERT_TRUE(Initialize(INITIALIZATION_NONE
));
580 current_browser()->profile()->GetHostContentSettingsMap()->SetContentSetting(
581 ContentSettingsPattern::FromURLNoWildcard(current_url()),
582 ContentSettingsPattern::FromURLNoWildcard(current_url()),
583 CONTENT_SETTINGS_TYPE_GEOLOCATION
, std::string(), CONTENT_SETTING_BLOCK
);
585 AddGeolocationWatch(false);
586 // Checks we have an error for this denied origin.
587 CheckStringValueFromJavascript("1", "geoGetLastError()");
588 // Checks prompt will not be created a second tab.
589 ASSERT_TRUE(Initialize(INITIALIZATION_NEWTAB
));
591 AddGeolocationWatch(false);
592 CheckStringValueFromJavascript("1", "geoGetLastError()");
595 IN_PROC_BROWSER_TEST_P(GeolocationBrowserTest
, NoPromptForAllowedOrigin
) {
596 ASSERT_TRUE(Initialize(INITIALIZATION_NONE
));
597 current_browser()->profile()->GetHostContentSettingsMap()->SetContentSetting(
598 ContentSettingsPattern::FromURLNoWildcard(current_url()),
599 ContentSettingsPattern::FromURLNoWildcard(current_url()),
600 CONTENT_SETTINGS_TYPE_GEOLOCATION
, std::string(), CONTENT_SETTING_ALLOW
);
601 // Checks no prompt will be created and there's no error callback.
603 AddGeolocationWatch(false);
604 CheckGeoposition(fake_latitude(), fake_longitude());
607 IN_PROC_BROWSER_TEST_P(GeolocationBrowserTest
, NoPromptForOffTheRecord
) {
608 // First, check prompt will be created for regular profile
609 ASSERT_TRUE(Initialize(INITIALIZATION_NONE
));
611 AddGeolocationWatch(true);
612 // Response will be persisted.
613 SetPromptResponse(current_url(), true);
614 CheckGeoposition(fake_latitude(), fake_longitude());
615 // Disables further prompts from this tab.
616 CheckStringValueFromJavascript("0", "geoSetMaxNavigateCount(0)");
617 // Go incognito, and checks no prompt will be created.
618 ASSERT_TRUE(Initialize(INITIALIZATION_OFFTHERECORD
));
620 AddGeolocationWatch(false);
621 CheckGeoposition(fake_latitude(), fake_longitude());
624 IN_PROC_BROWSER_TEST_P(GeolocationBrowserTest
, NoLeakFromOffTheRecord
) {
625 // First, check prompt will be created for incognito profile.
626 ASSERT_TRUE(Initialize(INITIALIZATION_OFFTHERECORD
));
628 AddGeolocationWatch(true);
629 // Response won't be persisted.
630 SetPromptResponse(current_url(), true);
631 CheckGeoposition(fake_latitude(), fake_longitude());
632 // Disables further prompts from this tab.
633 CheckStringValueFromJavascript("0", "geoSetMaxNavigateCount(0)");
634 // Go to the regular profile, prompt will be created.
635 ASSERT_TRUE(Initialize(INITIALIZATION_NONE
));
637 AddGeolocationWatch(true);
638 SetPromptResponse(current_url(), false);
639 CheckStringValueFromJavascript("1", "geoGetLastError()");
642 IN_PROC_BROWSER_TEST_P(GeolocationBrowserTest
, IFramesWithFreshPosition
) {
643 set_html_for_tests("/geolocation/iframes_different_origin.html");
644 ASSERT_TRUE(Initialize(INITIALIZATION_IFRAMES
));
646 LOG(WARNING
) << "frames loaded";
648 SetFrameHost("iframe_0");
649 AddGeolocationWatch(true);
650 SetPromptResponse(iframe_url(0), true);
651 CheckGeoposition(fake_latitude(), fake_longitude());
652 // Disables further prompts from this iframe.
653 CheckStringValueFromJavascript("0", "geoSetMaxNavigateCount(0)");
655 // Test second iframe from a different origin with a cached geoposition will
656 // create the prompt.
657 SetFrameHost("iframe_1");
658 AddGeolocationWatch(true);
660 // Back to the first frame, enable navigation and refresh geoposition.
661 SetFrameHost("iframe_0");
662 CheckStringValueFromJavascript("1", "geoSetMaxNavigateCount(1)");
663 double fresh_position_latitude
= 3.17;
664 double fresh_position_longitude
= 4.23;
665 content::WindowedNotificationObserver
observer(
666 content::NOTIFICATION_LOAD_STOP
,
667 content::Source
<NavigationController
>(
668 ¤t_browser()->tab_strip_model()->GetActiveWebContents()->
670 NotifyGeoposition(fresh_position_latitude
, fresh_position_longitude
);
672 CheckGeoposition(fresh_position_latitude
, fresh_position_longitude
);
674 // Disable navigation for this frame.
675 CheckStringValueFromJavascript("0", "geoSetMaxNavigateCount(0)");
677 // Now go ahead an authorize the second frame.
678 SetFrameHost("iframe_1");
679 // Infobar was displayed, allow access and check there's no error code.
680 SetPromptResponse(iframe_url(1), true);
681 LOG(WARNING
) << "Checking position...";
682 CheckGeoposition(fresh_position_latitude
, fresh_position_longitude
);
683 LOG(WARNING
) << "...done.";
686 IN_PROC_BROWSER_TEST_P(GeolocationBrowserTest
,
687 IFramesWithCachedPosition
) {
688 set_html_for_tests("/geolocation/iframes_different_origin.html");
689 ASSERT_TRUE(Initialize(INITIALIZATION_IFRAMES
));
692 SetFrameHost("iframe_0");
693 AddGeolocationWatch(true);
694 SetPromptResponse(iframe_url(0), true);
695 CheckGeoposition(fake_latitude(), fake_longitude());
697 // Refresh geoposition, but let's not yet create the watch on the second frame
698 // so that it'll fetch from cache.
699 double cached_position_latitude
= 5.67;
700 double cached_position_lognitude
= 8.09;
701 content::WindowedNotificationObserver
observer(
702 content::NOTIFICATION_LOAD_STOP
,
703 content::Source
<NavigationController
>(
704 ¤t_browser()->tab_strip_model()->GetActiveWebContents()->
706 NotifyGeoposition(cached_position_latitude
, cached_position_lognitude
);
708 CheckGeoposition(cached_position_latitude
, cached_position_lognitude
);
710 // Disable navigation for this frame.
711 CheckStringValueFromJavascript("0", "geoSetMaxNavigateCount(0)");
713 // Now go ahead and authorize the second frame.
714 SetFrameHost("iframe_1");
715 AddGeolocationWatch(true);
716 // WebKit will use its cache, but we also broadcast a position shortly
717 // afterwards. We're only interested in the first navigation for the success
718 // callback from the cached position.
719 CheckStringValueFromJavascript("1", "geoSetMaxNavigateCount(1)");
720 SetPromptResponse(iframe_url(1), true);
721 CheckGeoposition(cached_position_latitude
, cached_position_lognitude
);
724 IN_PROC_BROWSER_TEST_P(GeolocationBrowserTest
, CancelPermissionForFrame
) {
725 set_html_for_tests("/geolocation/iframes_different_origin.html");
726 ASSERT_TRUE(Initialize(INITIALIZATION_IFRAMES
));
728 LOG(WARNING
) << "frames loaded";
730 SetFrameHost("iframe_0");
731 AddGeolocationWatch(true);
732 SetPromptResponse(iframe_url(0), true);
733 CheckGeoposition(fake_latitude(), fake_longitude());
734 // Disables further prompts from this iframe.
735 CheckStringValueFromJavascript("0", "geoSetMaxNavigateCount(0)");
737 // Test second iframe from a different origin with a cached geoposition will
738 // create the prompt.
739 SetFrameHost("iframe_1");
740 AddGeolocationWatch(true);
742 // Change the iframe, and ensure the prompt is gone.
743 if (PermissionBubbleManager::Enabled()) {
744 WebContents
* web_contents
=
745 current_browser()->tab_strip_model()->GetActiveWebContents();
746 int num_bubbles_before_cancel
= GetBubblesQueueSize(
747 PermissionBubbleManager::FromWebContents(web_contents
));
748 IFrameLoader
change_iframe_1(current_browser(), 1, current_url());
749 int num_bubbles_after_cancel
= GetBubblesQueueSize(
750 PermissionBubbleManager::FromWebContents(web_contents
));
751 EXPECT_EQ(num_bubbles_before_cancel
, num_bubbles_after_cancel
+ 1);
753 InfoBarService
* infobar_service
= InfoBarService::FromWebContents(
754 current_browser()->tab_strip_model()->GetActiveWebContents());
755 size_t num_infobars_before_cancel
= infobar_service
->infobar_count();
756 IFrameLoader
change_iframe_1(current_browser(), 1, current_url());
757 size_t num_infobars_after_cancel
= infobar_service
->infobar_count();
758 EXPECT_EQ(num_infobars_before_cancel
, num_infobars_after_cancel
+ 1);
762 IN_PROC_BROWSER_TEST_P(GeolocationBrowserTest
, InvalidUrlRequest
) {
763 // Tests that an invalid URL (e.g. from a popup window) is rejected
764 // correctly. Also acts as a regression test for http://crbug.com/40478
765 set_html_for_tests("/geolocation/invalid_request_url.html");
766 ASSERT_TRUE(Initialize(INITIALIZATION_NONE
));
769 WebContents
* original_tab
=
770 current_browser()->tab_strip_model()->GetActiveWebContents();
771 CheckStringValueFromJavascript("1", "requestGeolocationFromInvalidUrl()");
772 CheckStringValueFromJavascriptForFrame("1", "isAlive()",
773 original_tab
->GetMainFrame());
776 IN_PROC_BROWSER_TEST_P(GeolocationBrowserTest
, NoPromptBeforeStart
) {
777 // See http://crbug.com/42789
778 set_html_for_tests("/geolocation/iframes_different_origin.html");
779 ASSERT_TRUE(Initialize(INITIALIZATION_IFRAMES
));
781 LOG(WARNING
) << "frames loaded";
783 // Access navigator.geolocation, but ensure it won't request permission.
784 SetFrameHost("iframe_1");
785 CheckStringValueFromJavascript("object", "geoAccessNavigatorGeolocation()");
787 SetFrameHost("iframe_0");
788 AddGeolocationWatch(true);
789 SetPromptResponse(iframe_url(0), true);
790 CheckGeoposition(fake_latitude(), fake_longitude());
791 CheckStringValueFromJavascript("0", "geoSetMaxNavigateCount(0)");
793 // Permission should be requested after adding a watch.
794 SetFrameHost("iframe_1");
795 AddGeolocationWatch(true);
796 SetPromptResponse(iframe_url(1), true);
797 CheckGeoposition(fake_latitude(), fake_longitude());
800 IN_PROC_BROWSER_TEST_P(GeolocationBrowserTest
, TwoWatchesInOneFrame
) {
801 set_html_for_tests("/geolocation/two_watches.html");
802 ASSERT_TRUE(Initialize(INITIALIZATION_NONE
));
804 // First, set the JavaScript to navigate when it receives |final_position|.
805 double final_position_latitude
= 3.17;
806 double final_position_longitude
= 4.23;
807 std::string script
= base::StringPrintf(
808 "window.domAutomationController.send(geoSetFinalPosition(%f, %f))",
809 final_position_latitude
, final_position_longitude
);
810 std::string js_result
;
811 EXPECT_TRUE(content::ExecuteScriptAndExtractString(
812 current_browser()->tab_strip_model()->GetActiveWebContents(), script
,
814 EXPECT_EQ(js_result
, "ok");
816 // Send a position which both geolocation watches will receive.
818 AddGeolocationWatch(true);
819 SetPromptResponse(current_url(), true);
820 CheckGeoposition(fake_latitude(), fake_longitude());
822 // The second watch will now have cancelled. Ensure an update still makes
823 // its way through to the first watcher.
824 content::WindowedNotificationObserver
observer(
825 content::NOTIFICATION_LOAD_STOP
,
826 content::Source
<NavigationController
>(
827 ¤t_browser()->tab_strip_model()->GetActiveWebContents()->
829 NotifyGeoposition(final_position_latitude
, final_position_longitude
);
831 CheckGeoposition(final_position_latitude
, final_position_longitude
);
834 IN_PROC_BROWSER_TEST_P(GeolocationBrowserTest
, TabDestroyed
) {
835 // This test triggers crbug.com/433877.
836 // TODO(felt): Reenable this test for permission bubbles once that's fixed.
837 if (PermissionBubbleManager::Enabled()) return;
839 set_html_for_tests("/geolocation/tab_destroyed.html");
840 ASSERT_TRUE(Initialize(INITIALIZATION_IFRAMES
));
843 SetFrameHost("iframe_0");
844 AddGeolocationWatch(true);
846 SetFrameHost("iframe_1");
847 AddGeolocationWatch(false);
849 SetFrameHost("iframe_2");
850 AddGeolocationWatch(false);
853 "window.domAutomationController.send(window.close());";
854 bool result
= content::ExecuteScript(
855 current_browser()->tab_strip_model()->GetActiveWebContents(), script
);
856 EXPECT_EQ(result
, true);
859 IN_PROC_BROWSER_TEST_P(GeolocationBrowserTest
, LastUsageUpdated
) {
860 ASSERT_TRUE(Initialize(INITIALIZATION_NONE
));
861 base::SimpleTestClock
* clock_
= new base::SimpleTestClock();
864 ->GetHostContentSettingsMap()
865 ->SetPrefClockForTesting(scoped_ptr
<base::Clock
>(clock_
));
866 clock_
->SetNow(base::Time::UnixEpoch() + base::TimeDelta::FromSeconds(10));
868 // Setting the permission should trigger the last usage.
869 current_browser()->profile()->GetHostContentSettingsMap()->SetContentSetting(
870 ContentSettingsPattern::FromURLNoWildcard(current_url()),
871 ContentSettingsPattern::FromURLNoWildcard(current_url()),
872 CONTENT_SETTINGS_TYPE_GEOLOCATION
,
874 CONTENT_SETTING_ALLOW
);
876 // Permission has been used at the starting time.
877 EXPECT_EQ(current_browser()
879 ->GetHostContentSettingsMap()
880 ->GetLastUsage(current_url().GetOrigin(),
881 current_url().GetOrigin(),
882 CONTENT_SETTINGS_TYPE_GEOLOCATION
)
886 clock_
->Advance(base::TimeDelta::FromSeconds(3));
888 // Watching should trigger the last usage update.
890 AddGeolocationWatch(false);
891 CheckGeoposition(fake_latitude(), fake_longitude());
893 // Last usage has been updated.
894 EXPECT_EQ(current_browser()
896 ->GetHostContentSettingsMap()
897 ->GetLastUsage(current_url().GetOrigin(),
898 current_url().GetOrigin(),
899 CONTENT_SETTINGS_TYPE_GEOLOCATION
)
904 INSTANTIATE_TEST_CASE_P(GeolocationBrowserTestWithParams
,
905 GeolocationBrowserTest
,
906 testing::Values(false));