1 // Copyright 2014 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 "extensions/browser/guest_view/web_view/web_view_guest.h"
7 #include "base/message_loop/message_loop.h"
8 #include "base/strings/stringprintf.h"
9 #include "base/strings/utf_string_conversions.h"
10 #include "components/browsing_data/storage_partition_http_cache_data_remover.h"
11 #include "components/guest_view/browser/guest_view_event.h"
12 #include "components/guest_view/browser/guest_view_manager.h"
13 #include "components/guest_view/common/guest_view_constants.h"
14 #include "components/web_cache/browser/web_cache_manager.h"
15 #include "content/public/browser/browser_context.h"
16 #include "content/public/browser/browser_thread.h"
17 #include "content/public/browser/child_process_security_policy.h"
18 #include "content/public/browser/native_web_keyboard_event.h"
19 #include "content/public/browser/navigation_entry.h"
20 #include "content/public/browser/notification_details.h"
21 #include "content/public/browser/notification_service.h"
22 #include "content/public/browser/notification_source.h"
23 #include "content/public/browser/notification_types.h"
24 #include "content/public/browser/render_process_host.h"
25 #include "content/public/browser/render_view_host.h"
26 #include "content/public/browser/render_widget_host_view.h"
27 #include "content/public/browser/resource_request_details.h"
28 #include "content/public/browser/site_instance.h"
29 #include "content/public/browser/storage_partition.h"
30 #include "content/public/browser/user_metrics.h"
31 #include "content/public/browser/web_contents.h"
32 #include "content/public/browser/web_contents_delegate.h"
33 #include "content/public/common/media_stream_request.h"
34 #include "content/public/common/page_zoom.h"
35 #include "content/public/common/result_codes.h"
36 #include "content/public/common/stop_find_action.h"
37 #include "content/public/common/url_constants.h"
38 #include "extensions/browser/api/declarative/rules_registry_service.h"
39 #include "extensions/browser/api/extensions_api_client.h"
40 #include "extensions/browser/api/guest_view/web_view/web_view_internal_api.h"
41 #include "extensions/browser/api/web_request/web_request_api.h"
42 #include "extensions/browser/extension_system.h"
43 #include "extensions/browser/guest_view/web_view/web_view_constants.h"
44 #include "extensions/browser/guest_view/web_view/web_view_content_script_manager.h"
45 #include "extensions/browser/guest_view/web_view/web_view_permission_helper.h"
46 #include "extensions/browser/guest_view/web_view/web_view_permission_types.h"
47 #include "extensions/browser/guest_view/web_view/web_view_renderer_state.h"
48 #include "extensions/common/constants.h"
49 #include "extensions/common/extension_messages.h"
50 #include "extensions/strings/grit/extensions_strings.h"
51 #include "ipc/ipc_message_macros.h"
52 #include "net/base/escape.h"
53 #include "net/base/net_errors.h"
54 #include "ui/base/models/simple_menu_model.h"
55 #include "url/url_constants.h"
57 using base::UserMetricsAction
;
58 using content::RenderFrameHost
;
59 using content::ResourceType
;
60 using content::StoragePartition
;
61 using content::WebContents
;
62 using guest_view::GuestViewBase
;
63 using guest_view::GuestViewEvent
;
64 using guest_view::GuestViewManager
;
65 using ui_zoom::ZoomController
;
67 namespace extensions
{
71 // Returns storage partition removal mask from web_view clearData mask. Note
72 // that storage partition mask is a subset of webview's data removal mask.
73 uint32
GetStoragePartitionRemovalMask(uint32 web_view_removal_mask
) {
75 if (web_view_removal_mask
& webview::WEB_VIEW_REMOVE_DATA_MASK_APPCACHE
)
76 mask
|= StoragePartition::REMOVE_DATA_MASK_APPCACHE
;
77 if (web_view_removal_mask
& webview::WEB_VIEW_REMOVE_DATA_MASK_COOKIES
)
78 mask
|= StoragePartition::REMOVE_DATA_MASK_COOKIES
;
79 if (web_view_removal_mask
& webview::WEB_VIEW_REMOVE_DATA_MASK_FILE_SYSTEMS
)
80 mask
|= StoragePartition::REMOVE_DATA_MASK_FILE_SYSTEMS
;
81 if (web_view_removal_mask
& webview::WEB_VIEW_REMOVE_DATA_MASK_INDEXEDDB
)
82 mask
|= StoragePartition::REMOVE_DATA_MASK_INDEXEDDB
;
83 if (web_view_removal_mask
& webview::WEB_VIEW_REMOVE_DATA_MASK_LOCAL_STORAGE
)
84 mask
|= StoragePartition::REMOVE_DATA_MASK_LOCAL_STORAGE
;
85 if (web_view_removal_mask
& webview::WEB_VIEW_REMOVE_DATA_MASK_WEBSQL
)
86 mask
|= StoragePartition::REMOVE_DATA_MASK_WEBSQL
;
91 std::string
WindowOpenDispositionToString(
92 WindowOpenDisposition window_open_disposition
) {
93 switch (window_open_disposition
) {
97 return "save_to_disk";
100 case NEW_BACKGROUND_TAB
:
101 return "new_background_tab";
102 case NEW_FOREGROUND_TAB
:
103 return "new_foreground_tab";
109 NOTREACHED() << "Unknown Window Open Disposition";
114 static std::string
TerminationStatusToString(base::TerminationStatus status
) {
116 case base::TERMINATION_STATUS_NORMAL_TERMINATION
:
118 case base::TERMINATION_STATUS_ABNORMAL_TERMINATION
:
119 case base::TERMINATION_STATUS_STILL_RUNNING
:
121 case base::TERMINATION_STATUS_PROCESS_WAS_KILLED
:
123 case base::TERMINATION_STATUS_PROCESS_CRASHED
:
125 case base::TERMINATION_STATUS_MAX_ENUM
:
128 NOTREACHED() << "Unknown Termination Status.";
132 std::string
GetStoragePartitionIdFromSiteURL(const GURL
& site_url
) {
133 const std::string
& partition_id
= site_url
.query();
134 bool persist_storage
= site_url
.path().find("persist") != std::string::npos
;
135 return (persist_storage
? webview::kPersistPrefix
: "") + partition_id
;
138 void ParsePartitionParam(const base::DictionaryValue
& create_params
,
139 std::string
* storage_partition_id
,
140 bool* persist_storage
) {
141 std::string partition_str
;
142 if (!create_params
.GetString(webview::kStoragePartitionId
, &partition_str
)) {
146 // Since the "persist:" prefix is in ASCII, StartsWith will work fine on
147 // UTF-8 encoded |partition_id|. If the prefix is a match, we can safely
148 // remove the prefix without splicing in the middle of a multi-byte codepoint.
149 // We can use the rest of the string as UTF-8 encoded one.
150 if (StartsWithASCII(partition_str
, "persist:", true)) {
151 size_t index
= partition_str
.find(":");
152 CHECK(index
!= std::string::npos
);
153 // It is safe to do index + 1, since we tested for the full prefix above.
154 *storage_partition_id
= partition_str
.substr(index
+ 1);
156 if (storage_partition_id
->empty()) {
157 // TODO(lazyboy): Better way to deal with this error.
160 *persist_storage
= true;
162 *storage_partition_id
= partition_str
;
163 *persist_storage
= false;
167 void RemoveWebViewEventListenersOnIOThread(
169 const std::string
& extension_id
,
170 int embedder_process_id
,
171 int view_instance_id
) {
172 DCHECK_CURRENTLY_ON(content::BrowserThread::IO
);
173 ExtensionWebRequestEventRouter::GetInstance()->RemoveWebViewEventListeners(
180 double ConvertZoomLevelToZoomFactor(double zoom_level
) {
181 double zoom_factor
= content::ZoomLevelToZoomFactor(zoom_level
);
182 // Because the conversion from zoom level to zoom factor isn't perfect, the
183 // resulting zoom factor is rounded to the nearest 6th decimal place.
184 zoom_factor
= round(zoom_factor
* 1000000) / 1000000;
191 GuestViewBase
* WebViewGuest::Create(content::WebContents
* owner_web_contents
) {
192 return new WebViewGuest(owner_web_contents
);
196 bool WebViewGuest::GetGuestPartitionConfigForSite(
198 std::string
* partition_domain
,
199 std::string
* partition_name
,
201 if (!site
.SchemeIs(content::kGuestScheme
))
204 // Since guest URLs are only used for packaged apps, there must be an app
206 CHECK(site
.has_host());
207 *partition_domain
= site
.host();
208 // Since persistence is optional, the path must either be empty or the
210 *in_memory
= (site
.path() != "/persist");
211 // The partition name is user supplied value, which we have encoded when the
212 // URL was created, so it needs to be decoded.
214 net::UnescapeURLComponent(site
.query(), net::UnescapeRule::NORMAL
);
219 const char WebViewGuest::Type
[] = "webview";
221 using WebViewKey
= std::pair
<int, int>;
222 using WebViewKeyToIDMap
= std::map
<WebViewKey
, int>;
223 static base::LazyInstance
<WebViewKeyToIDMap
> web_view_key_to_id_map
=
224 LAZY_INSTANCE_INITIALIZER
;
227 int WebViewGuest::GetOrGenerateRulesRegistryID(
228 int embedder_process_id
,
229 int webview_instance_id
) {
230 bool is_web_view
= embedder_process_id
&& webview_instance_id
;
232 return RulesRegistryService::kDefaultRulesRegistryID
;
234 WebViewKey key
= std::make_pair(embedder_process_id
, webview_instance_id
);
235 auto it
= web_view_key_to_id_map
.Get().find(key
);
236 if (it
!= web_view_key_to_id_map
.Get().end())
239 auto rph
= content::RenderProcessHost::FromID(embedder_process_id
);
240 int rules_registry_id
=
241 RulesRegistryService::Get(rph
->GetBrowserContext())->
242 GetNextRulesRegistryID();
243 web_view_key_to_id_map
.Get()[key
] = rules_registry_id
;
244 return rules_registry_id
;
248 int WebViewGuest::GetViewInstanceId(WebContents
* contents
) {
249 auto guest
= FromWebContents(contents
);
251 return guest_view::kInstanceIDNone
;
253 return guest
->view_instance_id();
256 bool WebViewGuest::CanRunInDetachedState() const {
260 void WebViewGuest::CreateWebContents(
261 const base::DictionaryValue
& create_params
,
262 const WebContentsCreatedCallback
& callback
) {
263 content::RenderProcessHost
* owner_render_process_host
=
264 owner_web_contents()->GetRenderProcessHost();
265 std::string storage_partition_id
;
266 bool persist_storage
= false;
267 ParsePartitionParam(create_params
, &storage_partition_id
, &persist_storage
);
268 // Validate that the partition id coming from the renderer is valid UTF-8,
269 // since we depend on this in other parts of the code, such as FilePath
270 // creation. If the validation fails, treat it as a bad message and kill the
272 if (!base::IsStringUTF8(storage_partition_id
)) {
273 content::RecordAction(
274 base::UserMetricsAction("BadMessageTerminate_BPGM"));
275 owner_render_process_host
->Shutdown(content::RESULT_CODE_KILLED_BAD_MESSAGE
,
277 callback
.Run(nullptr);
280 std::string url_encoded_partition
= net::EscapeQueryParamValue(
281 storage_partition_id
, false);
282 std::string partition_domain
= GetOwnerSiteURL().host();
283 GURL
guest_site(base::StringPrintf("%s://%s/%s?%s",
284 content::kGuestScheme
,
285 partition_domain
.c_str(),
286 persist_storage
? "persist" : "",
287 url_encoded_partition
.c_str()));
289 // If we already have a webview tag in the same app using the same storage
290 // partition, we should use the same SiteInstance so the existing tag and
291 // the new tag can script each other.
292 auto guest_view_manager
= GuestViewManager::FromBrowserContext(
293 owner_render_process_host
->GetBrowserContext());
294 content::SiteInstance
* guest_site_instance
=
295 guest_view_manager
->GetGuestSiteInstance(guest_site
);
296 if (!guest_site_instance
) {
297 // Create the SiteInstance in a new BrowsingInstance, which will ensure
298 // that webview tags are also not allowed to send messages across
299 // different partitions.
300 guest_site_instance
= content::SiteInstance::CreateForURL(
301 owner_render_process_host
->GetBrowserContext(), guest_site
);
303 WebContents::CreateParams
params(
304 owner_render_process_host
->GetBrowserContext(),
305 guest_site_instance
);
306 params
.guest_delegate
= this;
307 callback
.Run(WebContents::Create(params
));
310 void WebViewGuest::DidAttachToEmbedder() {
311 ApplyAttributes(*attach_params());
314 void WebViewGuest::DidDropLink(const GURL
& url
) {
315 scoped_ptr
<base::DictionaryValue
> args(new base::DictionaryValue());
316 args
->SetString(guest_view::kUrl
, url
.spec());
318 new GuestViewEvent(webview::kEventDropLink
, args
.Pass()));
321 void WebViewGuest::DidInitialize(const base::DictionaryValue
& create_params
) {
322 script_executor_
.reset(
323 new ScriptExecutor(web_contents(), &script_observers_
));
325 notification_registrar_
.Add(this,
326 content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME
,
327 content::Source
<WebContents
>(web_contents()));
329 notification_registrar_
.Add(this,
330 content::NOTIFICATION_RESOURCE_RECEIVED_REDIRECT
,
331 content::Source
<WebContents
>(web_contents()));
333 if (web_view_guest_delegate_
)
334 web_view_guest_delegate_
->OnDidInitialize();
335 AttachWebViewHelpers(web_contents());
337 rules_registry_id_
= GetOrGenerateRulesRegistryID(
338 owner_web_contents()->GetRenderProcessHost()->GetID(),
341 // We must install the mapping from guests to WebViews prior to resuming
342 // suspended resource loads so that the WebRequest API will catch resource
344 PushWebViewStateToIOThread();
346 ApplyAttributes(create_params
);
349 void WebViewGuest::AttachWebViewHelpers(WebContents
* contents
) {
350 if (web_view_guest_delegate_
)
351 web_view_guest_delegate_
->OnAttachWebViewHelpers(contents
);
352 web_view_permission_helper_
.reset(new WebViewPermissionHelper(this));
355 void WebViewGuest::ClearDataInternal(base::Time remove_since
,
357 const base::Closure
& callback
) {
358 uint32 storage_partition_removal_mask
=
359 GetStoragePartitionRemovalMask(removal_mask
);
360 if (!storage_partition_removal_mask
) {
364 content::StoragePartition
* partition
=
365 content::BrowserContext::GetStoragePartition(
366 web_contents()->GetBrowserContext(),
367 web_contents()->GetSiteInstance());
368 partition
->ClearData(
369 storage_partition_removal_mask
,
370 content::StoragePartition::QUOTA_MANAGED_STORAGE_MASK_ALL
, GURL(),
371 content::StoragePartition::OriginMatcherFunction(), remove_since
,
372 base::Time::Now(), callback
);
375 void WebViewGuest::GuestViewDidStopLoading() {
376 scoped_ptr
<base::DictionaryValue
> args(new base::DictionaryValue());
378 new GuestViewEvent(webview::kEventLoadStop
, args
.Pass()));
381 void WebViewGuest::EmbedderFullscreenToggled(bool entered_fullscreen
) {
382 is_embedder_fullscreen_
= entered_fullscreen
;
383 // If the embedder has got out of fullscreen, we get out of fullscreen
385 if (!entered_fullscreen
)
386 SetFullscreenState(false);
389 void WebViewGuest::EmbedderWillBeDestroyed() {
390 // Clean up rules registries for the webview.
391 RulesRegistryService::Get(browser_context())
392 ->RemoveRulesRegistriesByID(rules_registry_id_
);
393 WebViewKey
key(owner_web_contents()->GetRenderProcessHost()->GetID(),
395 web_view_key_to_id_map
.Get().erase(key
);
397 content::BrowserThread::PostTask(
398 content::BrowserThread::IO
,
401 &RemoveWebViewEventListenersOnIOThread
,
404 owner_web_contents()->GetRenderProcessHost()->GetID(),
405 view_instance_id()));
408 const char* WebViewGuest::GetAPINamespace() const {
409 return webview::kAPINamespace
;
412 int WebViewGuest::GetTaskPrefix() const {
413 return IDS_EXTENSION_TASK_MANAGER_WEBVIEW_TAG_PREFIX
;
416 void WebViewGuest::GuestDestroyed() {
417 // Clean up custom context menu items for this guest.
418 if (web_view_guest_delegate_
)
419 web_view_guest_delegate_
->OnGuestDestroyed();
420 RemoveWebViewStateFromIOThread(web_contents());
423 void WebViewGuest::GuestReady() {
424 // The guest RenderView should always live in an isolated guest process.
425 CHECK(web_contents()->GetRenderProcessHost()->IsIsolatedGuest());
426 Send(new ExtensionMsg_SetFrameName(web_contents()->GetRoutingID(), name_
));
428 // We don't want to accidentally set the opacity of an interstitial page.
429 // WebContents::GetRenderWidgetHostView will return the RWHV of an
430 // interstitial page if one is showing at this time. We only want opacity
431 // to apply to web pages.
432 if (allow_transparency_
) {
433 web_contents()->GetRenderViewHost()->GetView()->SetBackgroundColor(
434 SK_ColorTRANSPARENT
);
437 ->GetRenderViewHost()
439 ->SetBackgroundColorToDefault();
443 void WebViewGuest::GuestSizeChangedDueToAutoSize(const gfx::Size
& old_size
,
444 const gfx::Size
& new_size
) {
445 scoped_ptr
<base::DictionaryValue
> args(new base::DictionaryValue());
446 args
->SetInteger(webview::kOldHeight
, old_size
.height());
447 args
->SetInteger(webview::kOldWidth
, old_size
.width());
448 args
->SetInteger(webview::kNewHeight
, new_size
.height());
449 args
->SetInteger(webview::kNewWidth
, new_size
.width());
451 new GuestViewEvent(webview::kEventSizeChanged
, args
.Pass()));
454 bool WebViewGuest::IsAutoSizeSupported() const {
458 bool WebViewGuest::IsDragAndDropEnabled() const {
462 void WebViewGuest::GuestZoomChanged(double old_zoom_level
,
463 double new_zoom_level
) {
464 // Dispatch the zoomchange event.
465 double old_zoom_factor
= ConvertZoomLevelToZoomFactor(old_zoom_level
);
466 double new_zoom_factor
= ConvertZoomLevelToZoomFactor(new_zoom_level
);
467 scoped_ptr
<base::DictionaryValue
> args(new base::DictionaryValue());
468 args
->SetDouble(webview::kOldZoomFactor
, old_zoom_factor
);
469 args
->SetDouble(webview::kNewZoomFactor
, new_zoom_factor
);
471 new GuestViewEvent(webview::kEventZoomChange
, args
.Pass()));
474 void WebViewGuest::WillDestroy() {
475 if (!attached() && GetOpener())
476 GetOpener()->pending_new_windows_
.erase(this);
479 bool WebViewGuest::AddMessageToConsole(WebContents
* source
,
481 const base::string16
& message
,
483 const base::string16
& source_id
) {
484 scoped_ptr
<base::DictionaryValue
> args(new base::DictionaryValue());
485 // Log levels are from base/logging.h: LogSeverity.
486 args
->SetInteger(webview::kLevel
, level
);
487 args
->SetString(webview::kMessage
, message
);
488 args
->SetInteger(webview::kLine
, line_no
);
489 args
->SetString(webview::kSourceId
, source_id
);
491 new GuestViewEvent(webview::kEventConsoleMessage
, args
.Pass()));
495 void WebViewGuest::CloseContents(WebContents
* source
) {
496 scoped_ptr
<base::DictionaryValue
> args(new base::DictionaryValue());
498 new GuestViewEvent(webview::kEventClose
, args
.Pass()));
501 void WebViewGuest::FindReply(WebContents
* source
,
503 int number_of_matches
,
504 const gfx::Rect
& selection_rect
,
505 int active_match_ordinal
,
507 find_helper_
.FindReply(request_id
,
510 active_match_ordinal
,
514 double WebViewGuest::GetZoom() const {
516 ZoomController::FromWebContents(web_contents())->GetZoomLevel();
517 return ConvertZoomLevelToZoomFactor(zoom_level
);
520 ZoomController::ZoomMode
WebViewGuest::GetZoomMode() {
521 return ZoomController::FromWebContents(web_contents())->zoom_mode();
524 bool WebViewGuest::HandleContextMenu(
525 const content::ContextMenuParams
& params
) {
526 if (!web_view_guest_delegate_
)
528 return web_view_guest_delegate_
->HandleContextMenu(params
);
531 void WebViewGuest::HandleKeyboardEvent(
533 const content::NativeWebKeyboardEvent
& event
) {
534 if (HandleKeyboardShortcuts(event
))
537 GuestViewBase::HandleKeyboardEvent(source
, event
);
540 bool WebViewGuest::PreHandleGestureEvent(content::WebContents
* source
,
541 const blink::WebGestureEvent
& event
) {
542 return !allow_scaling_
&& GuestViewBase::PreHandleGestureEvent(source
, event
);
545 void WebViewGuest::LoadProgressChanged(content::WebContents
* source
,
547 scoped_ptr
<base::DictionaryValue
> args(new base::DictionaryValue());
548 args
->SetString(guest_view::kUrl
, web_contents()->GetURL().spec());
549 args
->SetDouble(webview::kProgress
, progress
);
551 new GuestViewEvent(webview::kEventLoadProgress
, args
.Pass()));
554 void WebViewGuest::LoadAbort(bool is_top_level
,
557 const std::string
& error_type
) {
558 scoped_ptr
<base::DictionaryValue
> args(new base::DictionaryValue());
559 args
->SetBoolean(guest_view::kIsTopLevel
, is_top_level
);
560 args
->SetString(guest_view::kUrl
, url
.possibly_invalid_spec());
561 args
->SetInteger(guest_view::kCode
, error_code
);
562 args
->SetString(guest_view::kReason
, error_type
);
564 new GuestViewEvent(webview::kEventLoadAbort
, args
.Pass()));
567 void WebViewGuest::CreateNewGuestWebViewWindow(
568 const content::OpenURLParams
& params
) {
569 GuestViewManager
* guest_manager
=
570 GuestViewManager::FromBrowserContext(browser_context());
571 // Set the attach params to use the same partition as the opener.
572 // We pull the partition information from the site's URL, which is of the
573 // form guest://site/{persist}?{partition_name}.
574 const GURL
& site_url
= web_contents()->GetSiteInstance()->GetSiteURL();
575 const std::string storage_partition_id
=
576 GetStoragePartitionIdFromSiteURL(site_url
);
577 base::DictionaryValue create_params
;
578 create_params
.SetString(webview::kStoragePartitionId
, storage_partition_id
);
580 guest_manager
->CreateGuest(WebViewGuest::Type
,
581 embedder_web_contents(),
583 base::Bind(&WebViewGuest::NewGuestWebViewCallback
,
584 weak_ptr_factory_
.GetWeakPtr(),
588 void WebViewGuest::NewGuestWebViewCallback(
589 const content::OpenURLParams
& params
,
590 content::WebContents
* guest_web_contents
) {
591 WebViewGuest
* new_guest
= WebViewGuest::FromWebContents(guest_web_contents
);
592 new_guest
->SetOpener(this);
594 // Take ownership of |new_guest|.
595 pending_new_windows_
.insert(
596 std::make_pair(new_guest
, NewWindowInfo(params
.url
, std::string())));
598 // Request permission to show the new window.
599 RequestNewWindowPermission(params
.disposition
,
602 new_guest
->web_contents());
605 // TODO(fsamuel): Find a reliable way to test the 'responsive' and
606 // 'unresponsive' events.
607 void WebViewGuest::RendererResponsive(content::WebContents
* source
) {
608 scoped_ptr
<base::DictionaryValue
> args(new base::DictionaryValue());
609 args
->SetInteger(webview::kProcessId
,
610 web_contents()->GetRenderProcessHost()->GetID());
612 new GuestViewEvent(webview::kEventResponsive
, args
.Pass()));
615 void WebViewGuest::RendererUnresponsive(content::WebContents
* source
) {
616 scoped_ptr
<base::DictionaryValue
> args(new base::DictionaryValue());
617 args
->SetInteger(webview::kProcessId
,
618 web_contents()->GetRenderProcessHost()->GetID());
620 new GuestViewEvent(webview::kEventUnresponsive
, args
.Pass()));
623 void WebViewGuest::Observe(int type
,
624 const content::NotificationSource
& source
,
625 const content::NotificationDetails
& details
) {
627 case content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME
: {
628 DCHECK_EQ(content::Source
<WebContents
>(source
).ptr(), web_contents());
629 if (content::Source
<WebContents
>(source
).ptr() == web_contents())
633 case content::NOTIFICATION_RESOURCE_RECEIVED_REDIRECT
: {
634 DCHECK_EQ(content::Source
<WebContents
>(source
).ptr(), web_contents());
635 content::ResourceRedirectDetails
* resource_redirect_details
=
636 content::Details
<content::ResourceRedirectDetails
>(details
).ptr();
637 bool is_top_level
= resource_redirect_details
->resource_type
==
638 content::RESOURCE_TYPE_MAIN_FRAME
;
639 LoadRedirect(resource_redirect_details
->url
,
640 resource_redirect_details
->new_url
,
645 NOTREACHED() << "Unexpected notification sent.";
650 void WebViewGuest::StartFindInternal(
651 const base::string16
& search_text
,
652 const blink::WebFindOptions
& options
,
653 scoped_refptr
<WebViewInternalFindFunction
> find_function
) {
654 find_helper_
.Find(web_contents(), search_text
, options
, find_function
);
657 void WebViewGuest::StopFindingInternal(content::StopFindAction action
) {
658 find_helper_
.CancelAllFindSessions();
659 web_contents()->StopFinding(action
);
662 bool WebViewGuest::Go(int relative_index
) {
663 content::NavigationController
& controller
= web_contents()->GetController();
664 if (!controller
.CanGoToOffset(relative_index
))
667 controller
.GoToOffset(relative_index
);
671 void WebViewGuest::Reload() {
672 // TODO(fsamuel): Don't check for repost because we don't want to show
673 // Chromium's repost warning. We might want to implement a separate API
674 // for registering a callback if a repost is about to happen.
675 web_contents()->GetController().Reload(false);
678 void WebViewGuest::SetUserAgentOverride(
679 const std::string
& user_agent_override
) {
680 is_overriding_user_agent_
= !user_agent_override
.empty();
681 if (is_overriding_user_agent_
) {
682 content::RecordAction(UserMetricsAction("WebView.Guest.OverrideUA"));
684 web_contents()->SetUserAgentOverride(user_agent_override
);
687 void WebViewGuest::Stop() {
688 web_contents()->Stop();
691 void WebViewGuest::Terminate() {
692 content::RecordAction(UserMetricsAction("WebView.Guest.Terminate"));
693 base::ProcessHandle process_handle
=
694 web_contents()->GetRenderProcessHost()->GetHandle();
696 web_contents()->GetRenderProcessHost()->Shutdown(
697 content::RESULT_CODE_KILLED
, false);
700 bool WebViewGuest::ClearData(base::Time remove_since
,
702 const base::Closure
& callback
) {
703 content::RecordAction(UserMetricsAction("WebView.Guest.ClearData"));
704 content::StoragePartition
* partition
=
705 content::BrowserContext::GetStoragePartition(
706 web_contents()->GetBrowserContext(),
707 web_contents()->GetSiteInstance());
712 if (removal_mask
& webview::WEB_VIEW_REMOVE_DATA_MASK_CACHE
) {
713 // First clear http cache data and then clear the rest in
714 // |ClearDataInternal|.
715 int render_process_id
= web_contents()->GetRenderProcessHost()->GetID();
716 // We need to clear renderer cache separately for our process because
717 // StoragePartitionHttpCacheDataRemover::ClearData() does not clear that.
718 web_cache::WebCacheManager::GetInstance()->Remove(render_process_id
);
719 web_cache::WebCacheManager::GetInstance()->ClearCacheForProcess(
722 base::Closure cache_removal_done_callback
= base::Bind(
723 &WebViewGuest::ClearDataInternal
, weak_ptr_factory_
.GetWeakPtr(),
724 remove_since
, removal_mask
, callback
);
725 // StoragePartitionHttpCacheDataRemover removes itself when it is done.
726 // components/, move |ClearCache| to WebViewGuest: http//crbug.com/471287.
727 browsing_data::StoragePartitionHttpCacheDataRemover::CreateForRange(
728 partition
, remove_since
, base::Time::Now())
729 ->Remove(cache_removal_done_callback
);
734 ClearDataInternal(remove_since
, removal_mask
, callback
);
738 WebViewGuest::WebViewGuest(content::WebContents
* owner_web_contents
)
739 : GuestView
<WebViewGuest
>(owner_web_contents
),
740 rules_registry_id_(RulesRegistryService::kInvalidRulesRegistryID
),
742 is_overriding_user_agent_(false),
743 allow_transparency_(false),
744 javascript_dialog_helper_(this),
745 allow_scaling_(false),
746 is_guest_fullscreen_(false),
747 is_embedder_fullscreen_(false),
748 last_fullscreen_permission_was_allowed_by_embedder_(false),
749 pending_zoom_factor_(0.0),
750 weak_ptr_factory_(this) {
751 web_view_guest_delegate_
.reset(
752 ExtensionsAPIClient::Get()->CreateWebViewGuestDelegate(this));
755 WebViewGuest::~WebViewGuest() {
758 void WebViewGuest::DidCommitProvisionalLoadForFrame(
759 content::RenderFrameHost
* render_frame_host
,
761 ui::PageTransition transition_type
) {
762 if (!render_frame_host
->GetParent()) {
764 // Handle a pending zoom if one exists.
765 if (pending_zoom_factor_
) {
766 SetZoom(pending_zoom_factor_
);
767 pending_zoom_factor_
= 0.0;
770 scoped_ptr
<base::DictionaryValue
> args(new base::DictionaryValue());
771 args
->SetString(guest_view::kUrl
, url
.spec());
772 args
->SetBoolean(guest_view::kIsTopLevel
, !render_frame_host
->GetParent());
773 args
->SetString(webview::kInternalBaseURLForDataURL
,
776 .GetLastCommittedEntry()
777 ->GetBaseURLForDataURL()
779 args
->SetInteger(webview::kInternalCurrentEntryIndex
,
780 web_contents()->GetController().GetCurrentEntryIndex());
781 args
->SetInteger(webview::kInternalEntryCount
,
782 web_contents()->GetController().GetEntryCount());
783 args
->SetInteger(webview::kInternalProcessId
,
784 web_contents()->GetRenderProcessHost()->GetID());
786 new GuestViewEvent(webview::kEventLoadCommit
, args
.Pass()));
788 find_helper_
.CancelAllFindSessions();
790 if (web_view_guest_delegate_
) {
791 web_view_guest_delegate_
->OnDidCommitProvisionalLoadForFrame(
792 !render_frame_host
->GetParent());
796 void WebViewGuest::DidFailProvisionalLoad(
797 content::RenderFrameHost
* render_frame_host
,
798 const GURL
& validated_url
,
800 const base::string16
& error_description
) {
801 LoadAbort(!render_frame_host
->GetParent(), validated_url
, error_code
,
802 net::ErrorToShortString(error_code
));
805 void WebViewGuest::DidStartProvisionalLoadForFrame(
806 content::RenderFrameHost
* render_frame_host
,
807 const GURL
& validated_url
,
809 bool is_iframe_srcdoc
) {
810 scoped_ptr
<base::DictionaryValue
> args(new base::DictionaryValue());
811 args
->SetString(guest_view::kUrl
, validated_url
.spec());
812 args
->SetBoolean(guest_view::kIsTopLevel
, !render_frame_host
->GetParent());
814 new GuestViewEvent(webview::kEventLoadStart
, args
.Pass()));
817 void WebViewGuest::DocumentLoadedInFrame(
818 content::RenderFrameHost
* render_frame_host
) {
819 if (web_view_guest_delegate_
)
820 web_view_guest_delegate_
->OnDocumentLoadedInFrame(render_frame_host
);
823 void WebViewGuest::RenderProcessGone(base::TerminationStatus status
) {
824 // Cancel all find sessions in progress.
825 find_helper_
.CancelAllFindSessions();
827 scoped_ptr
<base::DictionaryValue
> args(new base::DictionaryValue());
828 args
->SetInteger(webview::kProcessId
,
829 web_contents()->GetRenderProcessHost()->GetID());
830 args
->SetString(webview::kReason
, TerminationStatusToString(status
));
832 new GuestViewEvent(webview::kEventExit
, args
.Pass()));
835 void WebViewGuest::UserAgentOverrideSet(const std::string
& user_agent
) {
836 content::NavigationController
& controller
= web_contents()->GetController();
837 content::NavigationEntry
* entry
= controller
.GetVisibleEntry();
840 entry
->SetIsOverridingUserAgent(!user_agent
.empty());
841 web_contents()->GetController().Reload(false);
844 void WebViewGuest::FrameNameChanged(RenderFrameHost
* render_frame_host
,
845 const std::string
& name
) {
846 if (render_frame_host
->GetParent())
852 ReportFrameNameChange(name
);
855 void WebViewGuest::ReportFrameNameChange(const std::string
& name
) {
857 scoped_ptr
<base::DictionaryValue
> args(new base::DictionaryValue());
858 args
->SetString(webview::kName
, name
);
860 new GuestViewEvent(webview::kEventFrameNameChanged
, args
.Pass()));
863 void WebViewGuest::LoadHandlerCalled() {
864 scoped_ptr
<base::DictionaryValue
> args(new base::DictionaryValue());
866 new GuestViewEvent(webview::kEventContentLoad
, args
.Pass()));
869 void WebViewGuest::LoadRedirect(const GURL
& old_url
,
872 scoped_ptr
<base::DictionaryValue
> args(new base::DictionaryValue());
873 args
->SetBoolean(guest_view::kIsTopLevel
, is_top_level
);
874 args
->SetString(webview::kNewURL
, new_url
.spec());
875 args
->SetString(webview::kOldURL
, old_url
.spec());
877 new GuestViewEvent(webview::kEventLoadRedirect
, args
.Pass()));
880 void WebViewGuest::PushWebViewStateToIOThread() {
881 const GURL
& site_url
= web_contents()->GetSiteInstance()->GetSiteURL();
882 std::string partition_domain
;
883 std::string partition_id
;
885 if (!GetGuestPartitionConfigForSite(
886 site_url
, &partition_domain
, &partition_id
, &in_memory
)) {
891 WebViewRendererState::WebViewInfo web_view_info
;
892 web_view_info
.embedder_process_id
=
893 owner_web_contents()->GetRenderProcessHost()->GetID();
894 web_view_info
.instance_id
= view_instance_id();
895 web_view_info
.partition_id
= partition_id
;
896 web_view_info
.owner_host
= owner_host();
897 web_view_info
.rules_registry_id
= rules_registry_id_
;
899 // Get content scripts IDs added by the guest.
900 WebViewContentScriptManager
* manager
=
901 WebViewContentScriptManager::Get(browser_context());
903 web_view_info
.content_script_ids
= manager
->GetContentScriptIDSet(
904 web_view_info
.embedder_process_id
, web_view_info
.instance_id
);
906 content::BrowserThread::PostTask(
907 content::BrowserThread::IO
,
909 base::Bind(&WebViewRendererState::AddGuest
,
910 base::Unretained(WebViewRendererState::GetInstance()),
911 web_contents()->GetRenderProcessHost()->GetID(),
912 web_contents()->GetRoutingID(),
917 void WebViewGuest::RemoveWebViewStateFromIOThread(
918 WebContents
* web_contents
) {
919 content::BrowserThread::PostTask(
920 content::BrowserThread::IO
, FROM_HERE
,
922 &WebViewRendererState::RemoveGuest
,
923 base::Unretained(WebViewRendererState::GetInstance()),
924 web_contents
->GetRenderProcessHost()->GetID(),
925 web_contents
->GetRoutingID()));
928 void WebViewGuest::RequestMediaAccessPermission(
929 content::WebContents
* source
,
930 const content::MediaStreamRequest
& request
,
931 const content::MediaResponseCallback
& callback
) {
932 web_view_permission_helper_
->RequestMediaAccessPermission(source
,
937 bool WebViewGuest::CheckMediaAccessPermission(content::WebContents
* source
,
938 const GURL
& security_origin
,
939 content::MediaStreamType type
) {
940 return web_view_permission_helper_
->CheckMediaAccessPermission(
941 source
, security_origin
, type
);
944 void WebViewGuest::CanDownload(
945 content::RenderViewHost
* render_view_host
,
947 const std::string
& request_method
,
948 const base::Callback
<void(bool)>& callback
) {
949 web_view_permission_helper_
->CanDownload(render_view_host
,
955 void WebViewGuest::RequestPointerLockPermission(
957 bool last_unlocked_by_target
,
958 const base::Callback
<void(bool)>& callback
) {
959 web_view_permission_helper_
->RequestPointerLockPermission(
961 last_unlocked_by_target
,
965 void WebViewGuest::SignalWhenReady(const base::Closure
& callback
) {
966 auto manager
= WebViewContentScriptManager::Get(browser_context());
967 manager
->SignalOnScriptsLoaded(callback
);
970 void WebViewGuest::WillAttachToEmbedder() {
971 rules_registry_id_
= GetOrGenerateRulesRegistryID(
972 owner_web_contents()->GetRenderProcessHost()->GetID(),
975 // We must install the mapping from guests to WebViews prior to resuming
976 // suspended resource loads so that the WebRequest API will catch resource
978 PushWebViewStateToIOThread();
981 content::JavaScriptDialogManager
* WebViewGuest::GetJavaScriptDialogManager(
982 WebContents
* source
) {
983 return &javascript_dialog_helper_
;
986 void WebViewGuest::NavigateGuest(const std::string
& src
,
987 bool force_navigation
) {
991 GURL url
= ResolveURL(src
);
993 // We wait for all the content scripts to load and then navigate the guest
994 // if the navigation is embedder-initiated. For browser-initiated navigations,
995 // content scripts will be ready.
996 if (force_navigation
) {
998 base::Bind(&WebViewGuest::LoadURLWithParams
,
999 weak_ptr_factory_
.GetWeakPtr(), url
, content::Referrer(),
1000 ui::PAGE_TRANSITION_AUTO_TOPLEVEL
, force_navigation
));
1003 LoadURLWithParams(url
, content::Referrer(), ui::PAGE_TRANSITION_AUTO_TOPLEVEL
,
1007 bool WebViewGuest::HandleKeyboardShortcuts(
1008 const content::NativeWebKeyboardEvent
& event
) {
1009 // <webview> outside of Chrome Apps do not handle keyboard shortcuts.
1010 if (!GuestViewManager::FromBrowserContext(browser_context())->
1011 IsOwnedByExtension(this)) {
1015 if (event
.type
!= blink::WebInputEvent::RawKeyDown
)
1018 // If the user hits the escape key without any modifiers then unlock the
1019 // mouse if necessary.
1020 if ((event
.windowsKeyCode
== ui::VKEY_ESCAPE
) &&
1021 !(event
.modifiers
& blink::WebInputEvent::InputModifiers
)) {
1022 return web_contents()->GotResponseToLockMouseRequest(false);
1025 #if defined(OS_MACOSX)
1026 if (event
.modifiers
!= blink::WebInputEvent::MetaKey
)
1029 if (event
.windowsKeyCode
== ui::VKEY_OEM_4
) {
1034 if (event
.windowsKeyCode
== ui::VKEY_OEM_6
) {
1039 if (event
.windowsKeyCode
== ui::VKEY_BROWSER_BACK
) {
1044 if (event
.windowsKeyCode
== ui::VKEY_BROWSER_FORWARD
) {
1053 void WebViewGuest::ApplyAttributes(const base::DictionaryValue
& params
) {
1055 if (params
.GetString(webview::kAttributeName
, &name
)) {
1056 // If the guest window's name is empty, then the WebView tag's name is
1057 // assigned. Otherwise, the guest window's name takes precedence over the
1058 // WebView tag's name.
1063 ReportFrameNameChange(name_
);
1065 std::string user_agent_override
;
1066 params
.GetString(webview::kParameterUserAgentOverride
, &user_agent_override
);
1067 SetUserAgentOverride(user_agent_override
);
1069 bool allow_transparency
= false;
1070 if (params
.GetBoolean(webview::kAttributeAllowTransparency
,
1071 &allow_transparency
)) {
1072 // We need to set the background opaque flag after navigation to ensure that
1073 // there is a RenderWidgetHostView available.
1074 SetAllowTransparency(allow_transparency
);
1077 bool allow_scaling
= false;
1078 if (params
.GetBoolean(webview::kAttributeAllowScaling
, &allow_scaling
))
1079 SetAllowScaling(allow_scaling
);
1081 // Check for a pending zoom from before the first navigation.
1082 params
.GetDouble(webview::kInitialZoomFactor
, &pending_zoom_factor_
);
1084 bool is_pending_new_window
= false;
1086 // We need to do a navigation here if the target URL has changed between
1087 // the time the WebContents was created and the time it was attached.
1088 // We also need to do an initial navigation if a RenderView was never
1089 // created for the new window in cases where there is no referrer.
1090 auto it
= GetOpener()->pending_new_windows_
.find(this);
1091 if (it
!= GetOpener()->pending_new_windows_
.end()) {
1092 const NewWindowInfo
& new_window_info
= it
->second
;
1093 if (new_window_info
.changed
|| !web_contents()->HasOpener())
1094 NavigateGuest(new_window_info
.url
.spec(), false /* force_navigation */);
1096 // Once a new guest is attached to the DOM of the embedder page, then the
1097 // lifetime of the new guest is no longer managed by the opener guest.
1098 GetOpener()->pending_new_windows_
.erase(this);
1100 is_pending_new_window
= true;
1104 // Only read the src attribute if this is not a New Window API flow.
1105 if (!is_pending_new_window
) {
1107 if (params
.GetString(webview::kAttributeSrc
, &src
))
1108 NavigateGuest(src
, true /* force_navigation */);
1112 void WebViewGuest::ShowContextMenu(
1114 const WebViewGuestDelegate::MenuItemVector
* items
) {
1115 if (web_view_guest_delegate_
)
1116 web_view_guest_delegate_
->OnShowContextMenu(request_id
, items
);
1119 void WebViewGuest::SetName(const std::string
& name
) {
1124 Send(new ExtensionMsg_SetFrameName(routing_id(), name_
));
1127 void WebViewGuest::SetZoom(double zoom_factor
) {
1128 auto zoom_controller
= ZoomController::FromWebContents(web_contents());
1129 DCHECK(zoom_controller
);
1130 double zoom_level
= content::ZoomFactorToZoomLevel(zoom_factor
);
1131 zoom_controller
->SetZoomLevel(zoom_level
);
1134 void WebViewGuest::SetZoomMode(ZoomController::ZoomMode zoom_mode
) {
1135 ZoomController::FromWebContents(web_contents())->SetZoomMode(zoom_mode
);
1138 void WebViewGuest::SetAllowTransparency(bool allow
) {
1139 if (allow_transparency_
== allow
)
1142 allow_transparency_
= allow
;
1143 if (!web_contents()->GetRenderViewHost()->GetView())
1146 if (allow_transparency_
) {
1147 web_contents()->GetRenderViewHost()->GetView()->SetBackgroundColor(
1148 SK_ColorTRANSPARENT
);
1151 ->GetRenderViewHost()
1153 ->SetBackgroundColorToDefault();
1157 void WebViewGuest::SetAllowScaling(bool allow
) {
1158 allow_scaling_
= allow
;
1161 bool WebViewGuest::LoadDataWithBaseURL(const std::string
& data_url
,
1162 const std::string
& base_url
,
1163 const std::string
& virtual_url
,
1164 std::string
* error
) {
1165 // Make GURLs from URLs.
1166 const GURL data_gurl
= GURL(data_url
);
1167 const GURL base_gurl
= GURL(base_url
);
1168 const GURL virtual_gurl
= GURL(virtual_url
);
1170 // Check that the provided URLs are valid.
1171 // |data_url| must be a valid data URL.
1172 if (!data_gurl
.is_valid() || !data_gurl
.SchemeIs(url::kDataScheme
)) {
1173 base::SStringPrintf(
1174 error
, webview::kAPILoadDataInvalidDataURL
, data_url
.c_str());
1177 // |base_url| must be a valid URL.
1178 if (!base_gurl
.is_valid()) {
1179 base::SStringPrintf(
1180 error
, webview::kAPILoadDataInvalidBaseURL
, base_url
.c_str());
1183 // |virtual_url| must be a valid URL.
1184 if (!virtual_gurl
.is_valid()) {
1185 base::SStringPrintf(
1186 error
, webview::kAPILoadDataInvalidVirtualURL
, virtual_url
.c_str());
1190 // Set up the parameters to load |data_url| with the specified |base_url|.
1191 content::NavigationController::LoadURLParams
load_params(data_gurl
);
1192 load_params
.load_type
= content::NavigationController::LOAD_TYPE_DATA
;
1193 load_params
.base_url_for_data_url
= base_gurl
;
1194 load_params
.virtual_url_for_data_url
= virtual_gurl
;
1195 load_params
.override_user_agent
=
1196 content::NavigationController::UA_OVERRIDE_INHERIT
;
1198 // Navigate to the data URL.
1199 GuestViewBase::LoadURLWithParams(load_params
);
1204 void WebViewGuest::AddNewContents(content::WebContents
* source
,
1205 content::WebContents
* new_contents
,
1206 WindowOpenDisposition disposition
,
1207 const gfx::Rect
& initial_rect
,
1209 bool* was_blocked
) {
1211 *was_blocked
= false;
1212 RequestNewWindowPermission(disposition
,
1218 content::WebContents
* WebViewGuest::OpenURLFromTab(
1219 content::WebContents
* source
,
1220 const content::OpenURLParams
& params
) {
1221 // There are two use cases to consider from a security perspective:
1222 // 1.) Renderer-initiated navigation to chrome:// must always be blocked even
1223 // if the <webview> is in WebUI. This is handled by
1224 // WebViewGuest::LoadURLWithParams. WebViewGuest::NavigateGuest will also
1225 // call LoadURLWithParams. CreateNewGuestWebViewWindow creates a new
1226 // WebViewGuest which will call NavigateGuest in DidInitialize.
1227 // 2.) The Language Settings context menu item should always work, both in
1228 // Chrome Apps and WebUI. This is a browser initiated request and so
1229 // we pass it along to the embedder's WebContentsDelegate to get the
1230 // browser to perform the action for the <webview>.
1231 if (!params
.is_renderer_initiated
) {
1232 if (!owner_web_contents()->GetDelegate())
1234 return owner_web_contents()->GetDelegate()->OpenURLFromTab(
1235 owner_web_contents(), params
);
1238 // If the guest wishes to navigate away prior to attachment then we save the
1239 // navigation to perform upon attachment. Navigation initializes a lot of
1240 // state that assumes an embedder exists, such as RenderWidgetHostViewGuest.
1241 // Navigation also resumes resource loading which we don't want to allow
1242 // until attachment.
1244 WebViewGuest
* opener
= GetOpener();
1245 auto it
= opener
->pending_new_windows_
.find(this);
1246 if (it
== opener
->pending_new_windows_
.end())
1248 const NewWindowInfo
& info
= it
->second
;
1249 NewWindowInfo
new_window_info(params
.url
, info
.name
);
1250 new_window_info
.changed
= new_window_info
.url
!= info
.url
;
1251 it
->second
= new_window_info
;
1255 // This code path is taken if RenderFrameImpl::DecidePolicyForNavigation
1256 // decides that a fork should happen. At the time of writing this comment,
1257 // the only way a well behaving guest could hit this code path is if it
1258 // navigates to a URL that's associated with the default search engine.
1259 // This list of URLs is generated by chrome::GetSearchURLs. Validity checks
1260 // are performed inside LoadURLWithParams such that if the guest attempts
1261 // to navigate to a URL that it is not allowed to navigate to, a 'loadabort'
1262 // event will fire in the embedder, and the guest will be navigated to
1264 if (params
.disposition
== CURRENT_TAB
) {
1265 LoadURLWithParams(params
.url
, params
.referrer
, params
.transition
,
1266 true /* force_navigation */);
1267 return web_contents();
1270 // This code path is taken if Ctrl+Click, middle click or any of the
1271 // keyboard/mouse combinations are used to open a link in a new tab/window.
1272 // This code path is also taken on client-side redirects from about:blank.
1273 CreateNewGuestWebViewWindow(params
);
1277 void WebViewGuest::WebContentsCreated(WebContents
* source_contents
,
1278 int opener_render_frame_id
,
1279 const base::string16
& frame_name
,
1280 const GURL
& target_url
,
1281 content::WebContents
* new_contents
) {
1282 auto guest
= WebViewGuest::FromWebContents(new_contents
);
1284 guest
->SetOpener(this);
1285 std::string guest_name
= base::UTF16ToUTF8(frame_name
);
1286 guest
->name_
= guest_name
;
1287 pending_new_windows_
.insert(
1288 std::make_pair(guest
, NewWindowInfo(target_url
, guest_name
)));
1291 void WebViewGuest::EnterFullscreenModeForTab(content::WebContents
* web_contents
,
1292 const GURL
& origin
) {
1293 // Ask the embedder for permission.
1294 base::DictionaryValue request_info
;
1295 request_info
.SetString(webview::kOrigin
, origin
.spec());
1296 web_view_permission_helper_
->RequestPermission(
1297 WEB_VIEW_PERMISSION_TYPE_FULLSCREEN
, request_info
,
1298 base::Bind(&WebViewGuest::OnFullscreenPermissionDecided
,
1299 weak_ptr_factory_
.GetWeakPtr()),
1300 false /* allowed_by_default */);
1302 // TODO(lazyboy): Right now the guest immediately goes fullscreen within its
1303 // bounds. If the embedder denies the permission then we will see a flicker.
1304 // Once we have the ability to "cancel" a renderer/ fullscreen request:
1305 // http://crbug.com/466854 this won't be necessary and we should be
1306 // Calling SetFullscreenState(true) once the embedder allowed the request.
1307 // Otherwise we would cancel renderer/ fullscreen if the embedder denied.
1308 SetFullscreenState(true);
1311 void WebViewGuest::ExitFullscreenModeForTab(
1312 content::WebContents
* web_contents
) {
1313 SetFullscreenState(false);
1316 bool WebViewGuest::IsFullscreenForTabOrPending(
1317 const content::WebContents
* web_contents
) const {
1318 return is_guest_fullscreen_
;
1321 void WebViewGuest::LoadURLWithParams(const GURL
& url
,
1322 const content::Referrer
& referrer
,
1323 ui::PageTransition transition_type
,
1324 bool force_navigation
) {
1325 // Do not allow navigating a guest to schemes other than known safe schemes.
1326 // This will block the embedder trying to load unwanted schemes, e.g.
1328 bool scheme_is_blocked
=
1329 (!content::ChildProcessSecurityPolicy::GetInstance()->IsWebSafeScheme(
1331 !url
.SchemeIs(url::kAboutScheme
)) ||
1332 url
.SchemeIs(url::kJavaScriptScheme
);
1333 if (scheme_is_blocked
|| !url
.is_valid()) {
1334 LoadAbort(true /* is_top_level */, url
, net::ERR_ABORTED
,
1335 net::ErrorToShortString(net::ERR_ABORTED
));
1336 NavigateGuest(url::kAboutBlankURL
, false /* force_navigation */);
1340 if (!force_navigation
&& (src_
== url
))
1343 GURL
validated_url(url
);
1344 web_contents()->GetRenderProcessHost()->FilterURL(false, &validated_url
);
1345 // As guests do not swap processes on navigation, only navigations to
1346 // normal web URLs are supported. No protocol handlers are installed for
1347 // other schemes (e.g., WebUI or extensions), and no permissions or bindings
1348 // can be granted to the guest process.
1349 content::NavigationController::LoadURLParams
load_url_params(validated_url
);
1350 load_url_params
.referrer
= referrer
;
1351 load_url_params
.transition_type
= transition_type
;
1352 load_url_params
.extra_headers
= std::string();
1353 if (is_overriding_user_agent_
) {
1354 load_url_params
.override_user_agent
=
1355 content::NavigationController::UA_OVERRIDE_TRUE
;
1357 GuestViewBase::LoadURLWithParams(load_url_params
);
1359 src_
= validated_url
;
1362 void WebViewGuest::RequestNewWindowPermission(
1363 WindowOpenDisposition disposition
,
1364 const gfx::Rect
& initial_bounds
,
1366 content::WebContents
* new_contents
) {
1367 auto guest
= WebViewGuest::FromWebContents(new_contents
);
1370 auto it
= pending_new_windows_
.find(guest
);
1371 if (it
== pending_new_windows_
.end())
1373 const NewWindowInfo
& new_window_info
= it
->second
;
1375 // Retrieve the opener partition info if we have it.
1376 const GURL
& site_url
= new_contents
->GetSiteInstance()->GetSiteURL();
1377 std::string storage_partition_id
= GetStoragePartitionIdFromSiteURL(site_url
);
1379 base::DictionaryValue request_info
;
1380 request_info
.SetInteger(webview::kInitialHeight
, initial_bounds
.height());
1381 request_info
.SetInteger(webview::kInitialWidth
, initial_bounds
.width());
1382 request_info
.Set(webview::kTargetURL
,
1383 new base::StringValue(new_window_info
.url
.spec()));
1384 request_info
.Set(webview::kName
, new base::StringValue(new_window_info
.name
));
1385 request_info
.SetInteger(webview::kWindowID
, guest
->guest_instance_id());
1386 // We pass in partition info so that window-s created through newwindow
1387 // API can use it to set their partition attribute.
1388 request_info
.Set(webview::kStoragePartitionId
,
1389 new base::StringValue(storage_partition_id
));
1391 webview::kWindowOpenDisposition
,
1392 new base::StringValue(WindowOpenDispositionToString(disposition
)));
1394 web_view_permission_helper_
->
1395 RequestPermission(WEB_VIEW_PERMISSION_TYPE_NEW_WINDOW
,
1397 base::Bind(&WebViewGuest::OnWebViewNewWindowResponse
,
1398 weak_ptr_factory_
.GetWeakPtr(),
1399 guest
->guest_instance_id()),
1400 false /* allowed_by_default */);
1403 GURL
WebViewGuest::ResolveURL(const std::string
& src
) {
1404 if (!GuestViewManager::FromBrowserContext(browser_context())->
1405 IsOwnedByExtension(this)) {
1409 GURL
default_url(base::StringPrintf("%s://%s/",
1411 owner_host().c_str()));
1412 return default_url
.Resolve(src
);
1415 void WebViewGuest::OnWebViewNewWindowResponse(
1416 int new_window_instance_id
,
1418 const std::string
& user_input
) {
1420 WebViewGuest::From(owner_web_contents()->GetRenderProcessHost()->GetID(),
1421 new_window_instance_id
);
1429 void WebViewGuest::OnFullscreenPermissionDecided(
1431 const std::string
& user_input
) {
1432 last_fullscreen_permission_was_allowed_by_embedder_
= allowed
;
1433 SetFullscreenState(allowed
);
1436 bool WebViewGuest::GuestMadeEmbedderFullscreen() const {
1437 return last_fullscreen_permission_was_allowed_by_embedder_
&&
1438 is_embedder_fullscreen_
;
1441 void WebViewGuest::SetFullscreenState(bool is_fullscreen
) {
1442 if (is_fullscreen
== is_guest_fullscreen_
)
1445 bool was_fullscreen
= is_guest_fullscreen_
;
1446 is_guest_fullscreen_
= is_fullscreen
;
1447 // If the embedder entered fullscreen because of us, it should exit fullscreen
1448 // when we exit fullscreen.
1449 if (was_fullscreen
&& GuestMadeEmbedderFullscreen()) {
1450 // Dispatch a message so we can call document.webkitCancelFullscreen()
1452 scoped_ptr
<base::DictionaryValue
> args(new base::DictionaryValue());
1453 DispatchEventToView(
1454 new GuestViewEvent(webview::kEventExitFullscreen
, args
.Pass()));
1456 // Since we changed fullscreen state, sending a Resize message ensures that
1457 // renderer/ sees the change.
1458 web_contents()->GetRenderViewHost()->WasResized();
1461 } // namespace extensions