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 "chrome/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 "chrome/browser/chrome_notification_types.h"
11 #include "chrome/browser/content_settings/tab_specific_content_settings.h"
12 #include "chrome/browser/extensions/api/web_request/web_request_api.h"
13 #include "chrome/browser/extensions/api/webview/webview_api.h"
14 #include "chrome/browser/extensions/chrome_extension_web_contents_observer.h"
15 #include "chrome/browser/extensions/extension_renderer_state.h"
16 #include "chrome/browser/extensions/menu_manager.h"
17 #include "chrome/browser/extensions/script_executor.h"
18 #include "chrome/browser/favicon/favicon_tab_helper.h"
19 #include "chrome/browser/geolocation/geolocation_permission_context.h"
20 #include "chrome/browser/geolocation/geolocation_permission_context_factory.h"
21 #include "chrome/browser/guest_view/guest_view_constants.h"
22 #include "chrome/browser/guest_view/guest_view_manager.h"
23 #include "chrome/browser/guest_view/web_view/web_view_constants.h"
24 #include "chrome/browser/guest_view/web_view/web_view_permission_types.h"
25 #include "chrome/browser/renderer_context_menu/context_menu_delegate.h"
26 #include "chrome/browser/renderer_context_menu/render_view_context_menu.h"
27 #include "chrome/browser/ui/pdf/pdf_tab_helper.h"
28 #include "chrome/common/chrome_version_info.h"
29 #include "chrome/common/render_messages.h"
30 #include "content/public/browser/browser_thread.h"
31 #include "content/public/browser/child_process_security_policy.h"
32 #include "content/public/browser/host_zoom_map.h"
33 #include "content/public/browser/native_web_keyboard_event.h"
34 #include "content/public/browser/navigation_entry.h"
35 #include "content/public/browser/notification_details.h"
36 #include "content/public/browser/notification_service.h"
37 #include "content/public/browser/notification_source.h"
38 #include "content/public/browser/notification_types.h"
39 #include "content/public/browser/render_process_host.h"
40 #include "content/public/browser/render_view_host.h"
41 #include "content/public/browser/resource_request_details.h"
42 #include "content/public/browser/site_instance.h"
43 #include "content/public/browser/storage_partition.h"
44 #include "content/public/browser/user_metrics.h"
45 #include "content/public/browser/web_contents.h"
46 #include "content/public/browser/web_contents_delegate.h"
47 #include "content/public/common/media_stream_request.h"
48 #include "content/public/common/page_zoom.h"
49 #include "content/public/common/result_codes.h"
50 #include "content/public/common/stop_find_action.h"
51 #include "content/public/common/url_constants.h"
52 #include "extensions/common/constants.h"
53 #include "ipc/ipc_message_macros.h"
54 #include "net/base/escape.h"
55 #include "net/base/net_errors.h"
56 #include "third_party/WebKit/public/web/WebFindOptions.h"
57 #include "ui/base/models/simple_menu_model.h"
59 #if defined(ENABLE_PRINTING)
60 #if defined(ENABLE_FULL_PRINTING)
61 #include "chrome/browser/printing/print_preview_message_handler.h"
62 #include "chrome/browser/printing/print_view_manager.h"
64 #include "chrome/browser/printing/print_view_manager_basic.h"
65 #endif // defined(ENABLE_FULL_PRINTING)
66 #endif // defined(ENABLE_PRINTING)
68 #if defined(ENABLE_PLUGINS)
69 #include "chrome/browser/guest_view/web_view/plugin_permission_helper.h"
72 #if defined(OS_CHROMEOS)
73 #include "chrome/browser/chromeos/accessibility/accessibility_manager.h"
76 using base::UserMetricsAction;
77 using content::RenderFrameHost;
78 using content::WebContents;
82 std::string WindowOpenDispositionToString(
83 WindowOpenDisposition window_open_disposition) {
84 switch (window_open_disposition) {
88 return "save_to_disk";
91 case NEW_BACKGROUND_TAB:
92 return "new_background_tab";
93 case NEW_FOREGROUND_TAB:
94 return "new_foreground_tab";
100 NOTREACHED() << "Unknown Window Open Disposition";
105 static std::string TerminationStatusToString(base::TerminationStatus status) {
107 case base::TERMINATION_STATUS_NORMAL_TERMINATION:
109 case base::TERMINATION_STATUS_ABNORMAL_TERMINATION:
110 case base::TERMINATION_STATUS_STILL_RUNNING:
112 case base::TERMINATION_STATUS_PROCESS_WAS_KILLED:
114 case base::TERMINATION_STATUS_PROCESS_CRASHED:
115 #if defined(OS_ANDROID)
116 case base::TERMINATION_STATUS_OOM_PROTECTED:
119 case base::TERMINATION_STATUS_MAX_ENUM:
122 NOTREACHED() << "Unknown Termination Status.";
126 static std::string PermissionTypeToString(WebViewPermissionType type) {
128 case WEB_VIEW_PERMISSION_TYPE_DOWNLOAD:
129 return webview::kPermissionTypeDownload;
130 case WEB_VIEW_PERMISSION_TYPE_FILESYSTEM:
131 return webview::kPermissionTypeFileSystem;
132 case WEB_VIEW_PERMISSION_TYPE_GEOLOCATION:
133 return webview::kPermissionTypeGeolocation;
134 case WEB_VIEW_PERMISSION_TYPE_JAVASCRIPT_DIALOG:
135 return webview::kPermissionTypeDialog;
136 case WEB_VIEW_PERMISSION_TYPE_LOAD_PLUGIN:
137 return webview::kPermissionTypeLoadPlugin;
138 case WEB_VIEW_PERMISSION_TYPE_MEDIA:
139 return webview::kPermissionTypeMedia;
140 case WEB_VIEW_PERMISSION_TYPE_NEW_WINDOW:
141 return webview::kPermissionTypeNewWindow;
142 case WEB_VIEW_PERMISSION_TYPE_POINTER_LOCK:
143 return webview::kPermissionTypePointerLock;
146 return std::string();
150 std::string GetStoragePartitionIdFromSiteURL(const GURL& site_url) {
151 const std::string& partition_id = site_url.query();
152 bool persist_storage = site_url.path().find("persist") != std::string::npos;
153 return (persist_storage ? webview::kPersistPrefix : "") + partition_id;
156 void RemoveWebViewEventListenersOnIOThread(
158 const std::string& extension_id,
159 int embedder_process_id,
160 int view_instance_id) {
161 DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO));
162 ExtensionWebRequestEventRouter::GetInstance()->RemoveWebViewEventListeners(
169 void AttachWebViewHelpers(WebContents* contents) {
170 FaviconTabHelper::CreateForWebContents(contents);
171 extensions::ChromeExtensionWebContentsObserver::CreateForWebContents(
173 #if defined(ENABLE_PLUGINS)
174 PluginPermissionHelper::CreateForWebContents(contents);
176 #if defined(ENABLE_PRINTING)
177 #if defined(ENABLE_FULL_PRINTING)
178 printing::PrintViewManager::CreateForWebContents(contents);
179 printing::PrintPreviewMessageHandler::CreateForWebContents(contents);
181 printing::PrintViewManagerBasic::CreateForWebContents(contents);
182 #endif // defined(ENABLE_FULL_PRINTING)
183 #endif // defined(ENABLE_PRINTING)
184 PDFTabHelper::CreateForWebContents(contents);
189 WebViewGuest::WebViewGuest(int guest_instance_id,
190 WebContents* guest_web_contents,
191 const std::string& embedder_extension_id)
192 : GuestView<WebViewGuest>(guest_instance_id),
193 script_executor_(new extensions::ScriptExecutor(guest_web_contents,
194 &script_observers_)),
195 pending_context_menu_request_id_(0),
196 next_permission_request_id_(0),
197 is_overriding_user_agent_(false),
199 chromevox_injected_(false),
201 javascript_dialog_helper_(this) {
202 Init(guest_web_contents, embedder_extension_id);
203 notification_registrar_.Add(
204 this, content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME,
205 content::Source<WebContents>(guest_web_contents));
207 notification_registrar_.Add(
208 this, content::NOTIFICATION_RESOURCE_RECEIVED_REDIRECT,
209 content::Source<WebContents>(guest_web_contents));
211 #if defined(OS_CHROMEOS)
212 chromeos::AccessibilityManager* accessibility_manager =
213 chromeos::AccessibilityManager::Get();
214 CHECK(accessibility_manager);
215 accessibility_subscription_ = accessibility_manager->RegisterCallback(
216 base::Bind(&WebViewGuest::OnAccessibilityStatusChanged,
217 base::Unretained(this)));
220 AttachWebViewHelpers(guest_web_contents);
224 bool WebViewGuest::GetGuestPartitionConfigForSite(
226 std::string* partition_domain,
227 std::string* partition_name,
229 if (!site.SchemeIs(content::kGuestScheme))
232 // Since guest URLs are only used for packaged apps, there must be an app
234 CHECK(site.has_host());
235 *partition_domain = site.host();
236 // Since persistence is optional, the path must either be empty or the
238 *in_memory = (site.path() != "/persist");
239 // The partition name is user supplied value, which we have encoded when the
240 // URL was created, so it needs to be decoded.
242 net::UnescapeURLComponent(site.query(), net::UnescapeRule::NORMAL);
247 const char WebViewGuest::Type[] = "webview";
250 int WebViewGuest::GetViewInstanceId(WebContents* contents) {
251 WebViewGuest* guest = FromWebContents(contents);
253 return guestview::kInstanceIDNone;
255 return guest->view_instance_id();
259 void WebViewGuest::ParsePartitionParam(
260 const base::DictionaryValue* extra_params,
261 std::string* storage_partition_id,
262 bool* persist_storage) {
263 std::string partition_str;
264 if (!extra_params->GetString(webview::kStoragePartitionId, &partition_str)) {
268 // Since the "persist:" prefix is in ASCII, StartsWith will work fine on
269 // UTF-8 encoded |partition_id|. If the prefix is a match, we can safely
270 // remove the prefix without splicing in the middle of a multi-byte codepoint.
271 // We can use the rest of the string as UTF-8 encoded one.
272 if (StartsWithASCII(partition_str, "persist:", true)) {
273 size_t index = partition_str.find(":");
274 CHECK(index != std::string::npos);
275 // It is safe to do index + 1, since we tested for the full prefix above.
276 *storage_partition_id = partition_str.substr(index + 1);
278 if (storage_partition_id->empty()) {
279 // TODO(lazyboy): Better way to deal with this error.
282 *persist_storage = true;
284 *storage_partition_id = partition_str;
285 *persist_storage = false;
290 void WebViewGuest::RecordUserInitiatedUMA(const PermissionResponseInfo& info,
293 // Note that |allow| == true means the embedder explicitly allowed the
294 // request. For some requests they might still fail. An example of such
295 // scenario would be: an embedder allows geolocation request but doesn't
296 // have geolocation access on its own.
297 switch (info.permission_type) {
298 case WEB_VIEW_PERMISSION_TYPE_DOWNLOAD:
299 content::RecordAction(
300 UserMetricsAction("WebView.PermissionAllow.Download"));
302 case WEB_VIEW_PERMISSION_TYPE_FILESYSTEM:
303 content::RecordAction(
304 UserMetricsAction("WebView.PermissionAllow.FileSystem"));
306 case WEB_VIEW_PERMISSION_TYPE_GEOLOCATION:
307 content::RecordAction(
308 UserMetricsAction("WebView.PermissionAllow.Geolocation"));
310 case WEB_VIEW_PERMISSION_TYPE_JAVASCRIPT_DIALOG:
311 content::RecordAction(
312 UserMetricsAction("WebView.PermissionAllow.JSDialog"));
314 case WEB_VIEW_PERMISSION_TYPE_LOAD_PLUGIN:
315 content::RecordAction(
316 UserMetricsAction("WebView.Guest.PermissionAllow.PluginLoad"));
317 case WEB_VIEW_PERMISSION_TYPE_MEDIA:
318 content::RecordAction(
319 UserMetricsAction("WebView.PermissionAllow.Media"));
321 case WEB_VIEW_PERMISSION_TYPE_NEW_WINDOW:
322 content::RecordAction(
323 UserMetricsAction("BrowserPlugin.PermissionAllow.NewWindow"));
325 case WEB_VIEW_PERMISSION_TYPE_POINTER_LOCK:
326 content::RecordAction(
327 UserMetricsAction("WebView.PermissionAllow.PointerLock"));
333 switch (info.permission_type) {
334 case WEB_VIEW_PERMISSION_TYPE_DOWNLOAD:
335 content::RecordAction(
336 UserMetricsAction("WebView.PermissionDeny.Download"));
338 case WEB_VIEW_PERMISSION_TYPE_FILESYSTEM:
339 content::RecordAction(
340 UserMetricsAction("WebView.PermissionDeny.FileSystem"));
342 case WEB_VIEW_PERMISSION_TYPE_GEOLOCATION:
343 content::RecordAction(
344 UserMetricsAction("WebView.PermissionDeny.Geolocation"));
346 case WEB_VIEW_PERMISSION_TYPE_JAVASCRIPT_DIALOG:
347 content::RecordAction(
348 UserMetricsAction("WebView.PermissionDeny.JSDialog"));
350 case WEB_VIEW_PERMISSION_TYPE_LOAD_PLUGIN:
351 content::RecordAction(
352 UserMetricsAction("WebView.Guest.PermissionDeny.PluginLoad"));
354 case WEB_VIEW_PERMISSION_TYPE_MEDIA:
355 content::RecordAction(
356 UserMetricsAction("WebView.PermissionDeny.Media"));
358 case WEB_VIEW_PERMISSION_TYPE_NEW_WINDOW:
359 content::RecordAction(
360 UserMetricsAction("BrowserPlugin.PermissionDeny.NewWindow"));
362 case WEB_VIEW_PERMISSION_TYPE_POINTER_LOCK:
363 content::RecordAction(
364 UserMetricsAction("WebView.PermissionDeny.PointerLock"));
373 scoped_ptr<base::ListValue> WebViewGuest::MenuModelToValue(
374 const ui::SimpleMenuModel& menu_model) {
375 scoped_ptr<base::ListValue> items(new base::ListValue());
376 for (int i = 0; i < menu_model.GetItemCount(); ++i) {
377 base::DictionaryValue* item_value = new base::DictionaryValue();
378 // TODO(lazyboy): We need to expose some kind of enum equivalent of
379 // |command_id| instead of plain integers.
380 item_value->SetInteger(webview::kMenuItemCommandId,
381 menu_model.GetCommandIdAt(i));
382 item_value->SetString(webview::kMenuItemLabel, menu_model.GetLabelAt(i));
383 items->Append(item_value);
388 void WebViewGuest::DidAttachToEmbedder() {
390 if (extra_params()->GetString(webview::kName, &name)) {
391 // If the guest window's name is empty, then the WebView tag's name is
392 // assigned. Otherwise, the guest window's name takes precedence over the
393 // WebView tag's name.
397 ReportFrameNameChange(name_);
399 std::string user_agent_override;
400 if (extra_params()->GetString(webview::kParameterUserAgentOverride,
401 &user_agent_override)) {
402 SetUserAgentOverride(user_agent_override);
404 SetUserAgentOverride("");
408 if (extra_params()->GetString("src", &src) && !src.empty())
412 // We need to do a navigation here if the target URL has changed between
413 // the time the WebContents was created and the time it was attached.
414 // We also need to do an initial navigation if a RenderView was never
415 // created for the new window in cases where there is no referrer.
416 PendingWindowMap::iterator it =
417 GetOpener()->pending_new_windows_.find(this);
418 if (it != GetOpener()->pending_new_windows_.end()) {
419 const NewWindowInfo& new_window_info = it->second;
420 if (new_window_info.changed || !guest_web_contents()->HasOpener())
421 NavigateGuest(new_window_info.url.spec());
426 // Once a new guest is attached to the DOM of the embedder page, then the
427 // lifetime of the new guest is no longer managed by the opener guest.
428 GetOpener()->pending_new_windows_.erase(this);
432 void WebViewGuest::DidStopLoading() {
433 scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
434 DispatchEvent(new GuestViewBase::Event(webview::kEventLoadStop, args.Pass()));
437 void WebViewGuest::EmbedderDestroyed() {
438 // TODO(fsamuel): WebRequest event listeners for <webview> should survive
439 // reparenting of a <webview> within a single embedder. Right now, we keep
440 // around the browser state for the listener for the lifetime of the embedder.
441 // Ideally, the lifetime of the listeners should match the lifetime of the
442 // <webview> DOM node. Once http://crbug.com/156219 is resolved we can move
443 // the call to RemoveWebViewEventListenersOnIOThread back to
444 // WebViewGuest::WebContentsDestroyed.
445 content::BrowserThread::PostTask(
446 content::BrowserThread::IO,
449 &RemoveWebViewEventListenersOnIOThread,
450 browser_context(), embedder_extension_id(),
451 embedder_render_process_id(),
452 view_instance_id()));
455 void WebViewGuest::GuestDestroyed() {
456 // Clean up custom context menu items for this guest.
457 extensions::MenuManager* menu_manager = extensions::MenuManager::Get(
458 Profile::FromBrowserContext(browser_context()));
459 menu_manager->RemoveAllContextItems(extensions::MenuItem::ExtensionKey(
460 embedder_extension_id(), view_instance_id()));
462 RemoveWebViewFromExtensionRendererState(web_contents());
465 bool WebViewGuest::IsDragAndDropEnabled() const {
469 void WebViewGuest::WillDestroy() {
470 if (!attached() && GetOpener())
471 GetOpener()->pending_new_windows_.erase(this);
472 DestroyUnattachedWindows();
475 bool WebViewGuest::AddMessageToConsole(WebContents* source,
477 const base::string16& message,
479 const base::string16& source_id) {
480 scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
481 // Log levels are from base/logging.h: LogSeverity.
482 args->SetInteger(webview::kLevel, level);
483 args->SetString(webview::kMessage, message);
484 args->SetInteger(webview::kLine, line_no);
485 args->SetString(webview::kSourceId, source_id);
487 new GuestViewBase::Event(webview::kEventConsoleMessage, args.Pass()));
491 void WebViewGuest::CloseContents(WebContents* source) {
492 scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
493 DispatchEvent(new GuestViewBase::Event(webview::kEventClose, args.Pass()));
496 void WebViewGuest::FindReply(WebContents* source,
498 int number_of_matches,
499 const gfx::Rect& selection_rect,
500 int active_match_ordinal,
502 find_helper_.FindReply(request_id, number_of_matches, selection_rect,
503 active_match_ordinal, final_update);
506 bool WebViewGuest::HandleContextMenu(
507 const content::ContextMenuParams& params) {
508 ContextMenuDelegate* menu_delegate =
509 ContextMenuDelegate::FromWebContents(guest_web_contents());
510 DCHECK(menu_delegate);
512 pending_menu_ = menu_delegate->BuildMenu(guest_web_contents(), params);
514 // Pass it to embedder.
515 int request_id = ++pending_context_menu_request_id_;
516 scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
517 scoped_ptr<base::ListValue> items =
518 MenuModelToValue(pending_menu_->menu_model());
519 args->Set(webview::kContextMenuItems, items.release());
520 args->SetInteger(webview::kRequestId, request_id);
521 DispatchEvent(new GuestViewBase::Event(webview::kEventContextMenu,
526 void WebViewGuest::HandleKeyboardEvent(
528 const content::NativeWebKeyboardEvent& event) {
532 if (HandleKeyboardShortcuts(event))
535 // Send the unhandled keyboard events back to the embedder to reprocess them.
536 // TODO(fsamuel): This introduces the possibility of out-of-order keyboard
537 // events because the guest may be arbitrarily delayed when responding to
538 // keyboard events. In that time, the embedder may have received and processed
539 // additional key events. This needs to be fixed as soon as possible.
540 // See http://crbug.com/229882.
541 embedder_web_contents()->GetDelegate()->HandleKeyboardEvent(
542 web_contents(), event);
545 void WebViewGuest::LoadProgressChanged(content::WebContents* source,
547 scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
548 args->SetString(guestview::kUrl, guest_web_contents()->GetURL().spec());
549 args->SetDouble(webview::kProgress, progress);
551 new GuestViewBase::Event(webview::kEventLoadProgress, args.Pass()));
554 void WebViewGuest::LoadAbort(bool is_top_level,
556 const std::string& error_type) {
557 scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
558 args->SetBoolean(guestview::kIsTopLevel, is_top_level);
559 args->SetString(guestview::kUrl, url.possibly_invalid_spec());
560 args->SetString(guestview::kReason, error_type);
562 new GuestViewBase::Event(webview::kEventLoadAbort, args.Pass()));
565 void WebViewGuest::OnUpdateFrameName(bool is_top_level,
566 const std::string& name) {
573 ReportFrameNameChange(name);
576 WebViewGuest* WebViewGuest::CreateNewGuestWindow(
577 const content::OpenURLParams& params) {
578 GuestViewManager* guest_manager =
579 GuestViewManager::FromBrowserContext(browser_context());
580 // Allocate a new instance ID for the new guest.
581 int instance_id = guest_manager->GetNextInstanceID();
583 // Set the attach params to use the same partition as the opener.
584 // We pull the partition information from the site's URL, which is of the
585 // form guest://site/{persist}?{partition_name}.
586 const GURL& site_url = guest_web_contents()->GetSiteInstance()->GetSiteURL();
587 scoped_ptr<base::DictionaryValue> create_params(extra_params()->DeepCopy());
588 const std::string storage_partition_id =
589 GetStoragePartitionIdFromSiteURL(site_url);
590 create_params->SetString(webview::kStoragePartitionId, storage_partition_id);
592 WebContents* new_guest_web_contents =
593 guest_manager->CreateGuest(guest_web_contents()->GetSiteInstance(),
595 create_params.Pass());
596 WebViewGuest* new_guest =
597 WebViewGuest::FromWebContents(new_guest_web_contents);
598 new_guest->SetOpener(this);
600 // Take ownership of |new_guest|.
601 pending_new_windows_.insert(
602 std::make_pair(new_guest, NewWindowInfo(params.url, std::string())));
604 // Request permission to show the new window.
605 RequestNewWindowPermission(params.disposition, gfx::Rect(),
607 new_guest->guest_web_contents());
612 // TODO(fsamuel): Find a reliable way to test the 'responsive' and
613 // 'unresponsive' events.
614 void WebViewGuest::RendererResponsive(content::WebContents* source) {
615 scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
616 args->SetInteger(webview::kProcessId,
617 guest_web_contents()->GetRenderProcessHost()->GetID());
619 new GuestViewBase::Event(webview::kEventResponsive, args.Pass()));
622 void WebViewGuest::RendererUnresponsive(content::WebContents* source) {
623 scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
624 args->SetInteger(webview::kProcessId,
625 guest_web_contents()->GetRenderProcessHost()->GetID());
627 new GuestViewBase::Event(webview::kEventUnresponsive, args.Pass()));
630 void WebViewGuest::Observe(int type,
631 const content::NotificationSource& source,
632 const content::NotificationDetails& details) {
634 case content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME: {
635 DCHECK_EQ(content::Source<WebContents>(source).ptr(),
636 guest_web_contents());
637 if (content::Source<WebContents>(source).ptr() == guest_web_contents())
641 case content::NOTIFICATION_RESOURCE_RECEIVED_REDIRECT: {
642 DCHECK_EQ(content::Source<WebContents>(source).ptr(),
643 guest_web_contents());
644 content::ResourceRedirectDetails* resource_redirect_details =
645 content::Details<content::ResourceRedirectDetails>(details).ptr();
647 resource_redirect_details->resource_type == ResourceType::MAIN_FRAME;
648 LoadRedirect(resource_redirect_details->url,
649 resource_redirect_details->new_url,
654 NOTREACHED() << "Unexpected notification sent.";
659 double WebViewGuest::GetZoom() {
660 return current_zoom_factor_;
663 void WebViewGuest::Find(
664 const base::string16& search_text,
665 const blink::WebFindOptions& options,
666 scoped_refptr<extensions::WebviewFindFunction> find_function) {
667 find_helper_.Find(guest_web_contents(), search_text, options, find_function);
670 void WebViewGuest::StopFinding(content::StopFindAction action) {
671 find_helper_.CancelAllFindSessions();
672 guest_web_contents()->StopFinding(action);
675 void WebViewGuest::Go(int relative_index) {
676 guest_web_contents()->GetController().GoToOffset(relative_index);
679 void WebViewGuest::Reload() {
680 // TODO(fsamuel): Don't check for repost because we don't want to show
681 // Chromium's repost warning. We might want to implement a separate API
682 // for registering a callback if a repost is about to happen.
683 guest_web_contents()->GetController().Reload(false);
686 void WebViewGuest::RequestFileSystemPermission(
688 bool allowed_by_default,
689 const base::Callback<void(bool)>& callback) {
690 base::DictionaryValue request_info;
691 request_info.Set(guestview::kUrl, base::Value::CreateStringValue(url.spec()));
693 WEB_VIEW_PERMISSION_TYPE_FILESYSTEM,
695 base::Bind(&WebViewGuest::OnWebViewFileSystemPermissionResponse,
696 base::Unretained(this),
701 void WebViewGuest::OnWebViewFileSystemPermissionResponse(
702 const base::Callback<void(bool)>& callback,
704 const std::string& user_input) {
705 callback.Run(allow && attached());
708 void WebViewGuest::RequestGeolocationPermission(
710 const GURL& requesting_frame,
712 const base::Callback<void(bool)>& callback) {
713 base::DictionaryValue request_info;
714 request_info.Set(guestview::kUrl,
715 base::Value::CreateStringValue(requesting_frame.spec()));
716 request_info.Set(guestview::kUserGesture,
717 base::Value::CreateBooleanValue(user_gesture));
719 // It is safe to hold an unretained pointer to WebViewGuest because this
720 // callback is called from WebViewGuest::SetPermission.
721 const PermissionResponseCallback permission_callback =
722 base::Bind(&WebViewGuest::OnWebViewGeolocationPermissionResponse,
723 base::Unretained(this),
727 int request_id = RequestPermission(
728 WEB_VIEW_PERMISSION_TYPE_GEOLOCATION,
731 false /* allowed_by_default */);
732 bridge_id_to_request_id_map_[bridge_id] = request_id;
735 void WebViewGuest::OnWebViewGeolocationPermissionResponse(
738 const base::Callback<void(bool)>& callback,
740 const std::string& user_input) {
741 // The <webview> embedder has allowed the permission. We now need to make sure
742 // that the embedder has geolocation permission.
743 RemoveBridgeID(bridge_id);
745 if (!allow || !attached()) {
750 Profile* profile = Profile::FromBrowserContext(browser_context());
751 GeolocationPermissionContextFactory::GetForProfile(profile)->
752 RequestGeolocationPermission(
753 embedder_web_contents(),
754 // The geolocation permission request here is not initiated
755 // through WebGeolocationPermissionRequest. We are only interested
756 // in the fact whether the embedder/app has geolocation
757 // permission. Therefore we use an invalid |bridge_id|.
759 embedder_web_contents()->GetLastCommittedURL(),
765 void WebViewGuest::CancelGeolocationPermissionRequest(int bridge_id) {
766 int request_id = RemoveBridgeID(bridge_id);
767 RequestMap::iterator request_itr =
768 pending_permission_requests_.find(request_id);
770 if (request_itr == pending_permission_requests_.end())
773 pending_permission_requests_.erase(request_itr);
776 void WebViewGuest::OnWebViewMediaPermissionResponse(
777 const content::MediaStreamRequest& request,
778 const content::MediaResponseCallback& callback,
780 const std::string& user_input) {
781 if (!allow || !attached()) {
783 callback.Run(content::MediaStreamDevices(),
784 content::MEDIA_DEVICE_INVALID_STATE,
785 scoped_ptr<content::MediaStreamUI>());
788 if (!embedder_web_contents()->GetDelegate())
791 embedder_web_contents()->GetDelegate()->
792 RequestMediaAccessPermission(embedder_web_contents(), request, callback);
795 void WebViewGuest::OnWebViewDownloadPermissionResponse(
796 const base::Callback<void(bool)>& callback,
798 const std::string& user_input) {
799 callback.Run(allow && attached());
802 void WebViewGuest::OnWebViewPointerLockPermissionResponse(
803 const base::Callback<void(bool)>& callback,
805 const std::string& user_input) {
806 callback.Run(allow && attached());
809 WebViewGuest::SetPermissionResult WebViewGuest::SetPermission(
811 PermissionResponseAction action,
812 const std::string& user_input) {
813 RequestMap::iterator request_itr =
814 pending_permission_requests_.find(request_id);
816 if (request_itr == pending_permission_requests_.end())
817 return SET_PERMISSION_INVALID;
819 const PermissionResponseInfo& info = request_itr->second;
820 bool allow = (action == ALLOW) ||
821 ((action == DEFAULT) && info.allowed_by_default);
823 info.callback.Run(allow, user_input);
825 // Only record user initiated (i.e. non-default) actions.
826 if (action != DEFAULT)
827 RecordUserInitiatedUMA(info, allow);
829 pending_permission_requests_.erase(request_itr);
831 return allow ? SET_PERMISSION_ALLOWED : SET_PERMISSION_DENIED;
834 void WebViewGuest::SetUserAgentOverride(
835 const std::string& user_agent_override) {
838 is_overriding_user_agent_ = !user_agent_override.empty();
839 if (is_overriding_user_agent_) {
840 content::RecordAction(UserMetricsAction("WebView.Guest.OverrideUA"));
842 guest_web_contents()->SetUserAgentOverride(user_agent_override);
845 void WebViewGuest::Stop() {
846 guest_web_contents()->Stop();
849 void WebViewGuest::Terminate() {
850 content::RecordAction(UserMetricsAction("WebView.Guest.Terminate"));
851 base::ProcessHandle process_handle =
852 guest_web_contents()->GetRenderProcessHost()->GetHandle();
854 base::KillProcess(process_handle, content::RESULT_CODE_KILLED, false);
857 bool WebViewGuest::ClearData(const base::Time remove_since,
859 const base::Closure& callback) {
860 content::RecordAction(UserMetricsAction("WebView.Guest.ClearData"));
861 content::StoragePartition* partition =
862 content::BrowserContext::GetStoragePartition(
863 guest_web_contents()->GetBrowserContext(),
864 guest_web_contents()->GetSiteInstance());
869 partition->ClearData(
871 content::StoragePartition::QUOTA_MANAGED_STORAGE_MASK_ALL,
873 content::StoragePartition::OriginMatcherFunction(),
881 void WebViewGuest::FileSystemAccessedAsync(int render_process_id,
885 bool blocked_by_policy) {
886 WebViewGuest* guest =
887 WebViewGuest::FromFrameID(render_process_id, render_frame_id);
889 guest->RequestFileSystemPermission(
892 base::Bind(&WebViewGuest::FileSystemAccessedAsyncResponse,
900 void WebViewGuest::FileSystemAccessedAsyncResponse(int render_process_id,
905 TabSpecificContentSettings::FileSystemAccessed(
906 render_process_id, render_frame_id, url, !allowed);
907 content::RenderFrameHost* render_frame_host =
908 content::RenderFrameHost::FromID(render_process_id, render_frame_id);
909 if (!render_frame_host)
911 render_frame_host->Send(
912 new ChromeViewMsg_RequestFileSystemAccessAsyncResponse(
913 render_frame_id, request_id, allowed));
917 void WebViewGuest::FileSystemAccessedSync(int render_process_id,
920 bool blocked_by_policy,
921 IPC::Message* reply_msg) {
922 WebViewGuest* guest =
923 WebViewGuest::FromFrameID(render_process_id, render_frame_id);
925 guest->RequestFileSystemPermission(
928 base::Bind(&WebViewGuest::FileSystemAccessedSyncResponse,
936 void WebViewGuest::FileSystemAccessedSyncResponse(int render_process_id,
939 IPC::Message* reply_msg,
941 TabSpecificContentSettings::FileSystemAccessed(
942 render_process_id, render_frame_id, url, !allowed);
943 ChromeViewHostMsg_RequestFileSystemAccessSync::WriteReplyParams(reply_msg,
945 content::RenderFrameHost* render_frame_host =
946 content::RenderFrameHost::FromID(render_process_id, render_frame_id);
947 if (!render_frame_id)
949 render_frame_host->Send(reply_msg);
952 WebViewGuest::~WebViewGuest() {
955 void WebViewGuest::DidCommitProvisionalLoadForFrame(
957 const base::string16& frame_unique_name,
960 content::PageTransition transition_type,
961 content::RenderViewHost* render_view_host) {
962 find_helper_.CancelAllFindSessions();
964 scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
965 args->SetString(guestview::kUrl, url.spec());
966 args->SetBoolean(guestview::kIsTopLevel, is_main_frame);
967 args->SetInteger(webview::kInternalCurrentEntryIndex,
968 guest_web_contents()->GetController().GetCurrentEntryIndex());
969 args->SetInteger(webview::kInternalEntryCount,
970 guest_web_contents()->GetController().GetEntryCount());
971 args->SetInteger(webview::kInternalProcessId,
972 guest_web_contents()->GetRenderProcessHost()->GetID());
974 new GuestViewBase::Event(webview::kEventLoadCommit, args.Pass()));
976 // Update the current zoom factor for the new page.
977 current_zoom_factor_ = content::ZoomLevelToZoomFactor(
978 content::HostZoomMap::GetZoomLevel(guest_web_contents()));
981 chromevox_injected_ = false;
982 main_frame_id_ = frame_id;
986 void WebViewGuest::DidFailProvisionalLoad(
988 const base::string16& frame_unique_name,
990 const GURL& validated_url,
992 const base::string16& error_description,
993 content::RenderViewHost* render_view_host) {
994 // Translate the |error_code| into an error string.
995 std::string error_type(net::ErrorToString(error_code));
996 DCHECK(StartsWithASCII(error_type, "net::", true));
997 error_type.erase(0, 5);
998 LoadAbort(is_main_frame, validated_url, error_type);
1001 void WebViewGuest::DidStartProvisionalLoadForFrame(
1003 int64 parent_frame_id,
1005 const GURL& validated_url,
1007 bool is_iframe_srcdoc,
1008 content::RenderViewHost* render_view_host) {
1009 scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
1010 args->SetString(guestview::kUrl, validated_url.spec());
1011 args->SetBoolean(guestview::kIsTopLevel, is_main_frame);
1013 new GuestViewBase::Event(webview::kEventLoadStart, args.Pass()));
1016 void WebViewGuest::DocumentLoadedInFrame(
1018 content::RenderViewHost* render_view_host) {
1019 if (frame_id == main_frame_id_)
1020 InjectChromeVoxIfNeeded(render_view_host);
1023 bool WebViewGuest::OnMessageReceived(const IPC::Message& message,
1024 RenderFrameHost* render_frame_host) {
1025 bool handled = true;
1026 IPC_BEGIN_MESSAGE_MAP(WebViewGuest, message)
1027 IPC_MESSAGE_HANDLER(ChromeViewHostMsg_UpdateFrameName, OnUpdateFrameName)
1028 IPC_MESSAGE_UNHANDLED(handled = false)
1029 IPC_END_MESSAGE_MAP()
1033 void WebViewGuest::RenderProcessGone(base::TerminationStatus status) {
1034 // Cancel all find sessions in progress.
1035 find_helper_.CancelAllFindSessions();
1037 scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
1038 args->SetInteger(webview::kProcessId,
1039 guest_web_contents()->GetRenderProcessHost()->GetID());
1040 args->SetString(webview::kReason, TerminationStatusToString(status));
1041 DispatchEvent(new GuestViewBase::Event(webview::kEventExit, args.Pass()));
1044 void WebViewGuest::UserAgentOverrideSet(const std::string& user_agent) {
1047 content::NavigationController& controller =
1048 guest_web_contents()->GetController();
1049 content::NavigationEntry* entry = controller.GetVisibleEntry();
1052 entry->SetIsOverridingUserAgent(!user_agent.empty());
1053 guest_web_contents()->GetController().Reload(false);
1056 void WebViewGuest::RenderViewReady() {
1057 // The guest RenderView should always live in an isolated guest process.
1058 CHECK(guest_web_contents()->GetRenderProcessHost()->IsIsolatedGuest());
1059 Send(new ChromeViewMsg_SetName(guest_web_contents()->GetRoutingID(), name_));
1062 void WebViewGuest::ReportFrameNameChange(const std::string& name) {
1064 scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
1065 args->SetString(webview::kName, name);
1067 new GuestViewBase::Event(webview::kEventFrameNameChanged, args.Pass()));
1070 void WebViewGuest::LoadHandlerCalled() {
1071 scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
1073 new GuestViewBase::Event(webview::kEventContentLoad, args.Pass()));
1076 void WebViewGuest::LoadRedirect(const GURL& old_url,
1077 const GURL& new_url,
1078 bool is_top_level) {
1079 scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
1080 args->SetBoolean(guestview::kIsTopLevel, is_top_level);
1081 args->SetString(webview::kNewURL, new_url.spec());
1082 args->SetString(webview::kOldURL, old_url.spec());
1084 new GuestViewBase::Event(webview::kEventLoadRedirect, args.Pass()));
1087 void WebViewGuest::AddWebViewToExtensionRendererState() {
1088 const GURL& site_url = guest_web_contents()->GetSiteInstance()->GetSiteURL();
1089 std::string partition_domain;
1090 std::string partition_id;
1092 if (!GetGuestPartitionConfigForSite(
1093 site_url, &partition_domain, &partition_id, &in_memory)) {
1097 DCHECK(embedder_extension_id() == partition_domain);
1099 ExtensionRendererState::WebViewInfo web_view_info;
1100 web_view_info.embedder_process_id = embedder_render_process_id();
1101 web_view_info.instance_id = view_instance_id();
1102 web_view_info.partition_id = partition_id;
1103 web_view_info.embedder_extension_id = embedder_extension_id();
1105 content::BrowserThread::PostTask(
1106 content::BrowserThread::IO,
1108 base::Bind(&ExtensionRendererState::AddWebView,
1109 base::Unretained(ExtensionRendererState::GetInstance()),
1110 guest_web_contents()->GetRenderProcessHost()->GetID(),
1111 guest_web_contents()->GetRoutingID(),
1116 void WebViewGuest::RemoveWebViewFromExtensionRendererState(
1117 WebContents* web_contents) {
1118 content::BrowserThread::PostTask(
1119 content::BrowserThread::IO, FROM_HERE,
1121 &ExtensionRendererState::RemoveWebView,
1122 base::Unretained(ExtensionRendererState::GetInstance()),
1123 web_contents->GetRenderProcessHost()->GetID(),
1124 web_contents->GetRoutingID()));
1127 void WebViewGuest::SizeChanged(const gfx::Size& old_size,
1128 const gfx::Size& new_size) {
1129 scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
1130 args->SetInteger(webview::kOldHeight, old_size.height());
1131 args->SetInteger(webview::kOldWidth, old_size.width());
1132 args->SetInteger(webview::kNewHeight, new_size.height());
1133 args->SetInteger(webview::kNewWidth, new_size.width());
1135 new GuestViewBase::Event(webview::kEventSizeChanged, args.Pass()));
1138 void WebViewGuest::RequestMediaAccessPermission(
1139 content::WebContents* source,
1140 const content::MediaStreamRequest& request,
1141 const content::MediaResponseCallback& callback) {
1142 base::DictionaryValue request_info;
1145 base::Value::CreateStringValue(request.security_origin.spec()));
1146 RequestPermission(WEB_VIEW_PERMISSION_TYPE_MEDIA,
1148 base::Bind(&WebViewGuest::OnWebViewMediaPermissionResponse,
1149 base::Unretained(this),
1152 false /* allowed_by_default */);
1155 void WebViewGuest::CanDownload(
1156 content::RenderViewHost* render_view_host,
1158 const std::string& request_method,
1159 const base::Callback<void(bool)>& callback) {
1160 base::DictionaryValue request_info;
1163 base::Value::CreateStringValue(url.spec()));
1165 WEB_VIEW_PERMISSION_TYPE_DOWNLOAD,
1167 base::Bind(&WebViewGuest::OnWebViewDownloadPermissionResponse,
1168 base::Unretained(this),
1170 false /* allowed_by_default */);
1173 void WebViewGuest::RequestPointerLockPermission(
1175 bool last_unlocked_by_target,
1176 const base::Callback<void(bool)>& callback) {
1177 base::DictionaryValue request_info;
1178 request_info.Set(guestview::kUserGesture,
1179 base::Value::CreateBooleanValue(user_gesture));
1180 request_info.Set(webview::kLastUnlockedBySelf,
1181 base::Value::CreateBooleanValue(last_unlocked_by_target));
1182 request_info.Set(guestview::kUrl,
1183 base::Value::CreateStringValue(
1184 guest_web_contents()->GetLastCommittedURL().spec()));
1187 WEB_VIEW_PERMISSION_TYPE_POINTER_LOCK,
1189 base::Bind(&WebViewGuest::OnWebViewPointerLockPermissionResponse,
1190 base::Unretained(this),
1192 false /* allowed_by_default */);
1195 void WebViewGuest::WillAttachToEmbedder() {
1196 // We must install the mapping from guests to WebViews prior to resuming
1197 // suspended resource loads so that the WebRequest API will catch resource
1199 AddWebViewToExtensionRendererState();
1202 content::JavaScriptDialogManager*
1203 WebViewGuest::GetJavaScriptDialogManager() {
1204 return &javascript_dialog_helper_;
1207 content::ColorChooser* WebViewGuest::OpenColorChooser(
1208 WebContents* web_contents,
1210 const std::vector<content::ColorSuggestion>& suggestions) {
1211 if (!attached() || !embedder_web_contents()->GetDelegate())
1213 return embedder_web_contents()->GetDelegate()->OpenColorChooser(
1214 web_contents, color, suggestions);
1217 void WebViewGuest::RunFileChooser(WebContents* web_contents,
1218 const content::FileChooserParams& params) {
1219 if (!attached() || !embedder_web_contents()->GetDelegate())
1222 embedder_web_contents()->GetDelegate()->RunFileChooser(web_contents, params);
1225 void WebViewGuest::NavigateGuest(const std::string& src) {
1226 GURL url = ResolveURL(src);
1228 // Do not allow navigating a guest to schemes other than known safe schemes.
1229 // This will block the embedder trying to load unwanted schemes, e.g.
1230 // chrome://settings.
1231 bool scheme_is_blocked =
1232 (!content::ChildProcessSecurityPolicy::GetInstance()->IsWebSafeScheme(
1234 !url.SchemeIs(url::kAboutScheme)) ||
1235 url.SchemeIs(url::kJavaScriptScheme);
1236 if (scheme_is_blocked || !url.is_valid()) {
1237 std::string error_type(net::ErrorToString(net::ERR_ABORTED));
1238 DCHECK(StartsWithASCII(error_type, "net::", true));
1239 error_type.erase(0, 5);
1240 LoadAbort(true /* is_top_level */, url, error_type);
1244 GURL validated_url(url);
1245 guest_web_contents()->GetRenderProcessHost()->
1246 FilterURL(false, &validated_url);
1247 // As guests do not swap processes on navigation, only navigations to
1248 // normal web URLs are supported. No protocol handlers are installed for
1249 // other schemes (e.g., WebUI or extensions), and no permissions or bindings
1250 // can be granted to the guest process.
1251 LoadURLWithParams(validated_url,
1252 content::Referrer(),
1253 content::PAGE_TRANSITION_AUTO_TOPLEVEL,
1254 guest_web_contents());
1257 #if defined(OS_CHROMEOS)
1258 void WebViewGuest::OnAccessibilityStatusChanged(
1259 const chromeos::AccessibilityStatusEventDetails& details) {
1260 if (details.notification_type == chromeos::ACCESSIBILITY_MANAGER_SHUTDOWN) {
1261 accessibility_subscription_.reset();
1262 } else if (details.notification_type ==
1263 chromeos::ACCESSIBILITY_TOGGLE_SPOKEN_FEEDBACK) {
1264 if (details.enabled)
1265 InjectChromeVoxIfNeeded(guest_web_contents()->GetRenderViewHost());
1267 chromevox_injected_ = false;
1272 void WebViewGuest::InjectChromeVoxIfNeeded(
1273 content::RenderViewHost* render_view_host) {
1274 #if defined(OS_CHROMEOS)
1275 if (!chromevox_injected_) {
1276 chromeos::AccessibilityManager* manager =
1277 chromeos::AccessibilityManager::Get();
1278 if (manager && manager->IsSpokenFeedbackEnabled()) {
1279 manager->InjectChromeVox(render_view_host);
1280 chromevox_injected_ = true;
1286 int WebViewGuest::RemoveBridgeID(int bridge_id) {
1287 std::map<int, int>::iterator bridge_itr =
1288 bridge_id_to_request_id_map_.find(bridge_id);
1289 if (bridge_itr == bridge_id_to_request_id_map_.end())
1290 return webview::kInvalidPermissionRequestID;
1292 int request_id = bridge_itr->second;
1293 bridge_id_to_request_id_map_.erase(bridge_itr);
1297 int WebViewGuest::RequestPermission(
1298 WebViewPermissionType permission_type,
1299 const base::DictionaryValue& request_info,
1300 const PermissionResponseCallback& callback,
1301 bool allowed_by_default) {
1302 // If there are too many pending permission requests then reject this request.
1303 if (pending_permission_requests_.size() >=
1304 webview::kMaxOutstandingPermissionRequests) {
1305 // Let the stack unwind before we deny the permission request so that
1306 // objects held by the permission request are not destroyed immediately
1307 // after creation. This is to allow those same objects to be accessed again
1308 // in the same scope without fear of use after freeing.
1309 base::MessageLoop::current()->PostTask(
1311 base::Bind(&PermissionResponseCallback::Run,
1312 base::Owned(new PermissionResponseCallback(callback)),
1315 return webview::kInvalidPermissionRequestID;
1318 int request_id = next_permission_request_id_++;
1319 pending_permission_requests_[request_id] =
1320 PermissionResponseInfo(callback, permission_type, allowed_by_default);
1321 scoped_ptr<base::DictionaryValue> args(request_info.DeepCopy());
1322 args->SetInteger(webview::kRequestId, request_id);
1323 switch (permission_type) {
1324 case WEB_VIEW_PERMISSION_TYPE_NEW_WINDOW: {
1326 new GuestViewBase::Event(webview::kEventNewWindow, args.Pass()));
1329 case WEB_VIEW_PERMISSION_TYPE_JAVASCRIPT_DIALOG: {
1331 new GuestViewBase::Event(webview::kEventDialog, args.Pass()));
1335 args->SetString(webview::kPermission,
1336 PermissionTypeToString(permission_type));
1337 DispatchEvent(new GuestViewBase::Event(webview::kEventPermissionRequest,
1345 bool WebViewGuest::HandleKeyboardShortcuts(
1346 const content::NativeWebKeyboardEvent& event) {
1347 if (event.type != blink::WebInputEvent::RawKeyDown)
1350 // If the user hits the escape key without any modifiers then unlock the
1351 // mouse if necessary.
1352 if ((event.windowsKeyCode == ui::VKEY_ESCAPE) &&
1353 !(event.modifiers & blink::WebInputEvent::InputModifiers)) {
1354 return guest_web_contents()->GotResponseToLockMouseRequest(false);
1357 #if defined(OS_MACOSX)
1358 if (event.modifiers != blink::WebInputEvent::MetaKey)
1361 if (event.windowsKeyCode == ui::VKEY_OEM_4) {
1366 if (event.windowsKeyCode == ui::VKEY_OEM_6) {
1371 if (event.windowsKeyCode == ui::VKEY_BROWSER_BACK) {
1376 if (event.windowsKeyCode == ui::VKEY_BROWSER_FORWARD) {
1385 WebViewGuest::PermissionResponseInfo::PermissionResponseInfo()
1386 : permission_type(WEB_VIEW_PERMISSION_TYPE_UNKNOWN),
1387 allowed_by_default(false) {
1390 WebViewGuest::PermissionResponseInfo::PermissionResponseInfo(
1391 const PermissionResponseCallback& callback,
1392 WebViewPermissionType permission_type,
1393 bool allowed_by_default)
1394 : callback(callback),
1395 permission_type(permission_type),
1396 allowed_by_default(allowed_by_default) {
1399 WebViewGuest::PermissionResponseInfo::~PermissionResponseInfo() {
1402 void WebViewGuest::ShowContextMenu(int request_id,
1403 const MenuItemVector* items) {
1404 if (!pending_menu_.get())
1407 // Make sure this was the correct request.
1408 if (request_id != pending_context_menu_request_id_)
1411 // TODO(lazyboy): Implement.
1414 ContextMenuDelegate* menu_delegate =
1415 ContextMenuDelegate::FromWebContents(guest_web_contents());
1416 menu_delegate->ShowMenu(pending_menu_.Pass());
1419 void WebViewGuest::SetName(const std::string& name) {
1424 Send(new ChromeViewMsg_SetName(routing_id(), name_));
1427 void WebViewGuest::SetZoom(double zoom_factor) {
1428 double zoom_level = content::ZoomFactorToZoomLevel(zoom_factor);
1429 content::HostZoomMap::SetZoomLevel(guest_web_contents(), zoom_level);
1431 scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
1432 args->SetDouble(webview::kOldZoomFactor, current_zoom_factor_);
1433 args->SetDouble(webview::kNewZoomFactor, zoom_factor);
1435 new GuestViewBase::Event(webview::kEventZoomChange, args.Pass()));
1437 current_zoom_factor_ = zoom_factor;
1440 void WebViewGuest::AddNewContents(content::WebContents* source,
1441 content::WebContents* new_contents,
1442 WindowOpenDisposition disposition,
1443 const gfx::Rect& initial_pos,
1445 bool* was_blocked) {
1447 *was_blocked = false;
1448 RequestNewWindowPermission(disposition,
1454 content::WebContents* WebViewGuest::OpenURLFromTab(
1455 content::WebContents* source,
1456 const content::OpenURLParams& params) {
1457 // If the guest wishes to navigate away prior to attachment then we save the
1458 // navigation to perform upon attachment. Navigation initializes a lot of
1459 // state that assumes an embedder exists, such as RenderWidgetHostViewGuest.
1460 // Navigation also resumes resource loading which we don't want to allow
1461 // until attachment.
1463 WebViewGuest* opener = GetOpener();
1464 PendingWindowMap::iterator it =
1465 opener->pending_new_windows_.find(this);
1466 if (it == opener->pending_new_windows_.end())
1468 const NewWindowInfo& info = it->second;
1469 NewWindowInfo new_window_info(params.url, info.name);
1470 new_window_info.changed = new_window_info.url != info.url;
1471 it->second = new_window_info;
1474 if (params.disposition == CURRENT_TAB) {
1475 // This can happen for cross-site redirects.
1476 LoadURLWithParams(params.url, params.referrer, params.transition, source);
1480 return CreateNewGuestWindow(params)->guest_web_contents();
1483 void WebViewGuest::WebContentsCreated(WebContents* source_contents,
1484 int opener_render_frame_id,
1485 const base::string16& frame_name,
1486 const GURL& target_url,
1487 content::WebContents* new_contents) {
1488 WebViewGuest* guest = WebViewGuest::FromWebContents(new_contents);
1490 guest->SetOpener(this);
1491 std::string guest_name = base::UTF16ToUTF8(frame_name);
1492 guest->name_ = guest_name;
1493 pending_new_windows_.insert(
1494 std::make_pair(guest, NewWindowInfo(target_url, guest_name)));
1497 void WebViewGuest::LoadURLWithParams(const GURL& url,
1498 const content::Referrer& referrer,
1499 content::PageTransition transition_type,
1500 content::WebContents* web_contents) {
1501 content::NavigationController::LoadURLParams load_url_params(url);
1502 load_url_params.referrer = referrer;
1503 load_url_params.transition_type = transition_type;
1504 load_url_params.extra_headers = std::string();
1505 if (is_overriding_user_agent_) {
1506 load_url_params.override_user_agent =
1507 content::NavigationController::UA_OVERRIDE_TRUE;
1509 web_contents->GetController().LoadURLWithParams(load_url_params);
1512 void WebViewGuest::RequestNewWindowPermission(
1513 WindowOpenDisposition disposition,
1514 const gfx::Rect& initial_bounds,
1516 content::WebContents* new_contents) {
1517 WebViewGuest* guest = WebViewGuest::FromWebContents(new_contents);
1520 PendingWindowMap::iterator it = pending_new_windows_.find(guest);
1521 if (it == pending_new_windows_.end())
1523 const NewWindowInfo& new_window_info = it->second;
1525 // Retrieve the opener partition info if we have it.
1526 const GURL& site_url = new_contents->GetSiteInstance()->GetSiteURL();
1527 std::string storage_partition_id = GetStoragePartitionIdFromSiteURL(site_url);
1529 base::DictionaryValue request_info;
1530 request_info.Set(webview::kInitialHeight,
1531 base::Value::CreateIntegerValue(initial_bounds.height()));
1532 request_info.Set(webview::kInitialWidth,
1533 base::Value::CreateIntegerValue(initial_bounds.width()));
1534 request_info.Set(webview::kTargetURL,
1535 base::Value::CreateStringValue(new_window_info.url.spec()));
1536 request_info.Set(webview::kName,
1537 base::Value::CreateStringValue(new_window_info.name));
1538 request_info.Set(webview::kWindowID,
1539 base::Value::CreateIntegerValue(guest->guest_instance_id()));
1540 // We pass in partition info so that window-s created through newwindow
1541 // API can use it to set their partition attribute.
1542 request_info.Set(webview::kStoragePartitionId,
1543 base::Value::CreateStringValue(storage_partition_id));
1544 request_info.Set(webview::kWindowOpenDisposition,
1545 base::Value::CreateStringValue(
1546 WindowOpenDispositionToString(disposition)));
1548 RequestPermission(WEB_VIEW_PERMISSION_TYPE_NEW_WINDOW,
1550 base::Bind(&WebViewGuest::OnWebViewNewWindowResponse,
1551 base::Unretained(this),
1552 guest->guest_instance_id()),
1553 false /* allowed_by_default */);
1556 void WebViewGuest::DestroyUnattachedWindows() {
1557 // Destroy() reaches in and removes the WebViewGuest from its opener's
1558 // pending_new_windows_ set. To avoid mutating the set while iterating, we
1559 // create a copy of the pending new windows set and iterate over the copy.
1560 PendingWindowMap pending_new_windows(pending_new_windows_);
1561 // Clean up unattached new windows opened by this guest.
1562 for (PendingWindowMap::const_iterator it = pending_new_windows.begin();
1563 it != pending_new_windows.end(); ++it) {
1564 it->first->Destroy();
1566 // All pending windows should be removed from the set after Destroy() is
1567 // called on all of them.
1568 DCHECK(pending_new_windows_.empty());
1571 GURL WebViewGuest::ResolveURL(const std::string& src) {
1572 if (!in_extension()) {
1577 GURL default_url(base::StringPrintf("%s://%s/",
1578 extensions::kExtensionScheme,
1579 embedder_extension_id().c_str()));
1580 return default_url.Resolve(src);
1583 void WebViewGuest::OnWebViewNewWindowResponse(
1584 int new_window_instance_id,
1586 const std::string& user_input) {
1587 WebViewGuest* guest =
1588 WebViewGuest::From(embedder_render_process_id(), new_window_instance_id);