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 "chrome/browser/chrome_notification_types.h"
10 #include "chrome/browser/extensions/api/web_request/web_request_api.h"
11 #include "chrome/browser/extensions/api/webview/webview_api.h"
12 #include "chrome/browser/extensions/chrome_extension_web_contents_observer.h"
13 #include "chrome/browser/extensions/extension_renderer_state.h"
14 #include "chrome/browser/extensions/menu_manager.h"
15 #include "chrome/browser/extensions/script_executor.h"
16 #include "chrome/browser/favicon/favicon_tab_helper.h"
17 #include "chrome/browser/guest_view/guest_view_constants.h"
18 #include "chrome/browser/guest_view/web_view/web_view_constants.h"
19 #include "chrome/browser/guest_view/web_view/web_view_permission_types.h"
20 #include "chrome/browser/renderer_context_menu/context_menu_delegate.h"
21 #include "chrome/browser/renderer_context_menu/render_view_context_menu.h"
22 #include "chrome/common/chrome_version_info.h"
23 #include "content/public/browser/browser_thread.h"
24 #include "content/public/browser/geolocation_permission_context.h"
25 #include "content/public/browser/native_web_keyboard_event.h"
26 #include "content/public/browser/navigation_entry.h"
27 #include "content/public/browser/notification_details.h"
28 #include "content/public/browser/notification_service.h"
29 #include "content/public/browser/notification_source.h"
30 #include "content/public/browser/notification_types.h"
31 #include "content/public/browser/render_process_host.h"
32 #include "content/public/browser/resource_request_details.h"
33 #include "content/public/browser/site_instance.h"
34 #include "content/public/browser/storage_partition.h"
35 #include "content/public/browser/user_metrics.h"
36 #include "content/public/browser/web_contents.h"
37 #include "content/public/browser/web_contents_delegate.h"
38 #include "content/public/common/media_stream_request.h"
39 #include "content/public/common/page_zoom.h"
40 #include "content/public/common/result_codes.h"
41 #include "content/public/common/stop_find_action.h"
42 #include "extensions/common/constants.h"
43 #include "net/base/net_errors.h"
44 #include "third_party/WebKit/public/web/WebFindOptions.h"
45 #include "ui/base/models/simple_menu_model.h"
47 #if defined(ENABLE_PLUGINS)
48 #include "chrome/browser/guest_view/web_view/plugin_permission_helper.h"
51 #if defined(OS_CHROMEOS)
52 #include "chrome/browser/chromeos/accessibility/accessibility_manager.h"
55 using base::UserMetricsAction;
56 using content::WebContents;
60 static std::string TerminationStatusToString(base::TerminationStatus status) {
62 case base::TERMINATION_STATUS_NORMAL_TERMINATION:
64 case base::TERMINATION_STATUS_ABNORMAL_TERMINATION:
65 case base::TERMINATION_STATUS_STILL_RUNNING:
67 case base::TERMINATION_STATUS_PROCESS_WAS_KILLED:
69 case base::TERMINATION_STATUS_PROCESS_CRASHED:
70 #if defined(OS_ANDROID)
71 case base::TERMINATION_STATUS_OOM_PROTECTED:
74 case base::TERMINATION_STATUS_MAX_ENUM:
77 NOTREACHED() << "Unknown Termination Status.";
81 static std::string PermissionTypeToString(BrowserPluginPermissionType type) {
83 case BROWSER_PLUGIN_PERMISSION_TYPE_NEW_WINDOW:
84 return webview::kPermissionTypeNewWindow;
85 case BROWSER_PLUGIN_PERMISSION_TYPE_UNKNOWN:
89 WebViewPermissionType webview = static_cast<WebViewPermissionType>(type);
91 case WEB_VIEW_PERMISSION_TYPE_DOWNLOAD:
92 return webview::kPermissionTypeDownload;
93 case WEB_VIEW_PERMISSION_TYPE_GEOLOCATION:
94 return webview::kPermissionTypeGeolocation;
95 case WEB_VIEW_PERMISSION_TYPE_JAVASCRIPT_DIALOG:
96 return webview::kPermissionTypeDialog;
97 case WEB_VIEW_PERMISSION_TYPE_LOAD_PLUGIN:
98 return webview::kPermissionTypeLoadPlugin;
99 case WEB_VIEW_PERMISSION_TYPE_MEDIA:
100 return webview::kPermissionTypeMedia;
101 case WEB_VIEW_PERMISSION_TYPE_POINTER_LOCK:
102 return webview::kPermissionTypePointerLock;
107 return std::string();
110 void RemoveWebViewEventListenersOnIOThread(
112 const std::string& extension_id,
113 int embedder_process_id,
114 int view_instance_id) {
115 DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO));
116 ExtensionWebRequestEventRouter::GetInstance()->RemoveWebViewEventListeners(
123 void AttachWebViewHelpers(WebContents* contents) {
124 FaviconTabHelper::CreateForWebContents(contents);
125 extensions::ChromeExtensionWebContentsObserver::CreateForWebContents(
127 #if defined(ENABLE_PLUGINS)
128 PluginPermissionHelper::CreateForWebContents(contents);
134 WebViewGuest::WebViewGuest(WebContents* guest_web_contents,
135 const std::string& embedder_extension_id,
136 const base::WeakPtr<GuestViewBase>& opener)
137 : GuestView<WebViewGuest>(guest_web_contents,
138 embedder_extension_id,
140 WebContentsObserver(guest_web_contents),
141 script_executor_(new extensions::ScriptExecutor(guest_web_contents,
142 &script_observers_)),
143 pending_context_menu_request_id_(0),
144 next_permission_request_id_(0),
145 is_overriding_user_agent_(false),
146 pending_reload_on_attachment_(false),
148 chromevox_injected_(false),
150 javascript_dialog_helper_(this) {
151 notification_registrar_.Add(
152 this, content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME,
153 content::Source<WebContents>(guest_web_contents));
155 notification_registrar_.Add(
156 this, content::NOTIFICATION_RESOURCE_RECEIVED_REDIRECT,
157 content::Source<WebContents>(guest_web_contents));
159 #if defined(OS_CHROMEOS)
160 chromeos::AccessibilityManager* accessibility_manager =
161 chromeos::AccessibilityManager::Get();
162 CHECK(accessibility_manager);
163 accessibility_subscription_ = accessibility_manager->RegisterCallback(
164 base::Bind(&WebViewGuest::OnAccessibilityStatusChanged,
165 base::Unretained(this)));
168 AttachWebViewHelpers(guest_web_contents);
172 const char WebViewGuest::Type[] = "webview";
175 int WebViewGuest::GetViewInstanceId(WebContents* contents) {
176 WebViewGuest* guest = FromWebContents(contents);
178 return guestview::kInstanceIDNone;
180 return guest->view_instance_id();
184 void WebViewGuest::RecordUserInitiatedUMA(const PermissionResponseInfo& info,
187 // Note that |allow| == true means the embedder explicitly allowed the
188 // request. For some requests they might still fail. An example of such
189 // scenario would be: an embedder allows geolocation request but doesn't
190 // have geolocation access on its own.
191 switch (info.permission_type) {
192 case BROWSER_PLUGIN_PERMISSION_TYPE_NEW_WINDOW:
193 content::RecordAction(
194 UserMetricsAction("BrowserPlugin.PermissionAllow.NewWindow"));
196 case BROWSER_PLUGIN_PERMISSION_TYPE_UNKNOWN:
199 WebViewPermissionType webview_permission_type =
200 static_cast<WebViewPermissionType>(info.permission_type);
201 switch (webview_permission_type) {
202 case WEB_VIEW_PERMISSION_TYPE_DOWNLOAD:
203 content::RecordAction(
204 UserMetricsAction("WebView.PermissionAllow.Download"));
206 case WEB_VIEW_PERMISSION_TYPE_GEOLOCATION:
207 content::RecordAction(
208 UserMetricsAction("WebView.PermissionAllow.Geolocation"));
210 case WEB_VIEW_PERMISSION_TYPE_JAVASCRIPT_DIALOG:
211 content::RecordAction(
212 UserMetricsAction("WebView.PermissionAllow.JSDialog"));
214 case WEB_VIEW_PERMISSION_TYPE_LOAD_PLUGIN:
215 content::RecordAction(
216 UserMetricsAction("WebView.Guest.PermissionAllow.PluginLoad"));
217 case WEB_VIEW_PERMISSION_TYPE_MEDIA:
218 content::RecordAction(
219 UserMetricsAction("WebView.PermissionAllow.Media"));
221 case WEB_VIEW_PERMISSION_TYPE_POINTER_LOCK:
222 content::RecordAction(
223 UserMetricsAction("WebView.PermissionAllow.PointerLock"));
231 switch (info.permission_type) {
232 case BROWSER_PLUGIN_PERMISSION_TYPE_NEW_WINDOW:
233 content::RecordAction(
234 UserMetricsAction("BrowserPlugin.PermissionDeny.NewWindow"));
236 case BROWSER_PLUGIN_PERMISSION_TYPE_UNKNOWN:
239 WebViewPermissionType webview_permission_type =
240 static_cast<WebViewPermissionType>(info.permission_type);
241 switch (webview_permission_type) {
242 case WEB_VIEW_PERMISSION_TYPE_DOWNLOAD:
243 content::RecordAction(
244 UserMetricsAction("WebView.PermissionDeny.Download"));
246 case WEB_VIEW_PERMISSION_TYPE_GEOLOCATION:
247 content::RecordAction(
248 UserMetricsAction("WebView.PermissionDeny.Geolocation"));
250 case WEB_VIEW_PERMISSION_TYPE_JAVASCRIPT_DIALOG:
251 content::RecordAction(
252 UserMetricsAction("WebView.PermissionDeny.JSDialog"));
254 case WEB_VIEW_PERMISSION_TYPE_LOAD_PLUGIN:
255 content::RecordAction(
256 UserMetricsAction("WebView.Guest.PermissionDeny.PluginLoad"));
257 case WEB_VIEW_PERMISSION_TYPE_MEDIA:
258 content::RecordAction(
259 UserMetricsAction("WebView.PermissionDeny.Media"));
261 case WEB_VIEW_PERMISSION_TYPE_POINTER_LOCK:
262 content::RecordAction(
263 UserMetricsAction("WebView.PermissionDeny.PointerLock"));
274 scoped_ptr<base::ListValue> WebViewGuest::MenuModelToValue(
275 const ui::SimpleMenuModel& menu_model) {
276 scoped_ptr<base::ListValue> items(new base::ListValue());
277 for (int i = 0; i < menu_model.GetItemCount(); ++i) {
278 base::DictionaryValue* item_value = new base::DictionaryValue();
279 // TODO(lazyboy): We need to expose some kind of enum equivalent of
280 // |command_id| instead of plain integers.
281 item_value->SetInteger(webview::kMenuItemCommandId,
282 menu_model.GetCommandIdAt(i));
283 item_value->SetString(webview::kMenuItemLabel, menu_model.GetLabelAt(i));
284 items->Append(item_value);
289 void WebViewGuest::Attach(WebContents* embedder_web_contents,
290 const base::DictionaryValue& args) {
291 std::string user_agent_override;
292 if (args.GetString(webview::kParameterUserAgentOverride,
293 &user_agent_override)) {
294 SetUserAgentOverride(user_agent_override);
296 SetUserAgentOverride("");
299 GuestViewBase::Attach(embedder_web_contents, args);
301 AddWebViewToExtensionRendererState();
304 bool WebViewGuest::HandleContextMenu(
305 const content::ContextMenuParams& params) {
306 ContextMenuDelegate* menu_delegate =
307 ContextMenuDelegate::FromWebContents(guest_web_contents());
308 DCHECK(menu_delegate);
310 pending_menu_ = menu_delegate->BuildMenu(guest_web_contents(), params);
312 // Pass it to embedder.
313 int request_id = ++pending_context_menu_request_id_;
314 scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
315 scoped_ptr<base::ListValue> items =
316 MenuModelToValue(pending_menu_->menu_model());
317 args->Set(webview::kContextMenuItems, items.release());
318 args->SetInteger(webview::kRequestId, request_id);
319 DispatchEvent(new GuestViewBase::Event(webview::kEventContextMenu,
324 void WebViewGuest::AddMessageToConsole(int32 level,
325 const base::string16& message,
327 const base::string16& source_id) {
328 scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
329 // Log levels are from base/logging.h: LogSeverity.
330 args->SetInteger(webview::kLevel, level);
331 args->SetString(webview::kMessage, message);
332 args->SetInteger(webview::kLine, line_no);
333 args->SetString(webview::kSourceId, source_id);
335 new GuestViewBase::Event(webview::kEventConsoleMessage, args.Pass()));
338 void WebViewGuest::Close() {
339 scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
340 DispatchEvent(new GuestViewBase::Event(webview::kEventClose, args.Pass()));
343 void WebViewGuest::DidAttach() {
344 if (pending_reload_on_attachment_) {
345 pending_reload_on_attachment_ = false;
346 guest_web_contents()->GetController().Reload(false);
350 void WebViewGuest::EmbedderDestroyed() {
351 // TODO(fsamuel): WebRequest event listeners for <webview> should survive
352 // reparenting of a <webview> within a single embedder. Right now, we keep
353 // around the browser state for the listener for the lifetime of the embedder.
354 // Ideally, the lifetime of the listeners should match the lifetime of the
355 // <webview> DOM node. Once http://crbug.com/156219 is resolved we can move
356 // the call to RemoveWebViewEventListenersOnIOThread back to
357 // WebViewGuest::WebContentsDestroyed.
358 content::BrowserThread::PostTask(
359 content::BrowserThread::IO,
362 &RemoveWebViewEventListenersOnIOThread,
363 browser_context(), embedder_extension_id(),
364 embedder_render_process_id(),
365 view_instance_id()));
368 void WebViewGuest::FindReply(int request_id,
369 int number_of_matches,
370 const gfx::Rect& selection_rect,
371 int active_match_ordinal,
373 find_helper_.FindReply(request_id, number_of_matches, selection_rect,
374 active_match_ordinal, final_update);
377 void WebViewGuest::GuestProcessGone(base::TerminationStatus status) {
378 // Cancel all find sessions in progress.
379 find_helper_.CancelAllFindSessions();
381 scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
382 args->SetInteger(webview::kProcessId,
383 guest_web_contents()->GetRenderProcessHost()->GetID());
384 args->SetString(webview::kReason, TerminationStatusToString(status));
385 DispatchEvent(new GuestViewBase::Event(webview::kEventExit, args.Pass()));
388 bool WebViewGuest::HandleKeyboardEvent(
389 const content::NativeWebKeyboardEvent& event) {
390 if (event.type != blink::WebInputEvent::RawKeyDown)
393 #if defined(OS_MACOSX)
394 if (event.modifiers != blink::WebInputEvent::MetaKey)
397 if (event.windowsKeyCode == ui::VKEY_OEM_4) {
402 if (event.windowsKeyCode == ui::VKEY_OEM_6) {
407 if (event.windowsKeyCode == ui::VKEY_BROWSER_BACK) {
412 if (event.windowsKeyCode == ui::VKEY_BROWSER_FORWARD) {
420 bool WebViewGuest::IsDragAndDropEnabled() {
424 bool WebViewGuest::IsOverridingUserAgent() const {
425 return is_overriding_user_agent_;
428 void WebViewGuest::LoadProgressed(double progress) {
429 scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
430 args->SetString(guestview::kUrl, guest_web_contents()->GetURL().spec());
431 args->SetDouble(webview::kProgress, progress);
433 new GuestViewBase::Event(webview::kEventLoadProgress, args.Pass()));
436 void WebViewGuest::LoadAbort(bool is_top_level,
438 const std::string& error_type) {
439 scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
440 args->SetBoolean(guestview::kIsTopLevel, is_top_level);
441 args->SetString(guestview::kUrl, url.possibly_invalid_spec());
442 args->SetString(guestview::kReason, error_type);
444 new GuestViewBase::Event(webview::kEventLoadAbort, args.Pass()));
447 // TODO(fsamuel): Find a reliable way to test the 'responsive' and
448 // 'unresponsive' events.
449 void WebViewGuest::RendererResponsive() {
450 scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
451 args->SetInteger(webview::kProcessId,
452 guest_web_contents()->GetRenderProcessHost()->GetID());
454 new GuestViewBase::Event(webview::kEventResponsive, args.Pass()));
457 void WebViewGuest::RendererUnresponsive() {
458 scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
459 args->SetInteger(webview::kProcessId,
460 guest_web_contents()->GetRenderProcessHost()->GetID());
462 new GuestViewBase::Event(webview::kEventUnresponsive, args.Pass()));
465 void WebViewGuest::RequestPermission(
466 BrowserPluginPermissionType permission_type,
467 const base::DictionaryValue& request_info,
468 const PermissionResponseCallback& callback,
469 bool allowed_by_default) {
470 RequestPermissionInternal(permission_type,
476 void WebViewGuest::Observe(int type,
477 const content::NotificationSource& source,
478 const content::NotificationDetails& details) {
480 case content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME: {
481 DCHECK_EQ(content::Source<WebContents>(source).ptr(),
482 guest_web_contents());
483 if (content::Source<WebContents>(source).ptr() == guest_web_contents())
487 case content::NOTIFICATION_RESOURCE_RECEIVED_REDIRECT: {
488 DCHECK_EQ(content::Source<WebContents>(source).ptr(),
489 guest_web_contents());
490 content::ResourceRedirectDetails* resource_redirect_details =
491 content::Details<content::ResourceRedirectDetails>(details).ptr();
493 resource_redirect_details->resource_type == ResourceType::MAIN_FRAME;
494 LoadRedirect(resource_redirect_details->url,
495 resource_redirect_details->new_url,
500 NOTREACHED() << "Unexpected notification sent.";
505 void WebViewGuest::SetZoom(double zoom_factor) {
506 double zoom_level = content::ZoomFactorToZoomLevel(zoom_factor);
507 guest_web_contents()->SetZoomLevel(zoom_level);
509 scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
510 args->SetDouble(webview::kOldZoomFactor, current_zoom_factor_);
511 args->SetDouble(webview::kNewZoomFactor, zoom_factor);
513 new GuestViewBase::Event(webview::kEventZoomChange, args.Pass()));
515 current_zoom_factor_ = zoom_factor;
518 double WebViewGuest::GetZoom() {
519 return current_zoom_factor_;
522 void WebViewGuest::Find(
523 const base::string16& search_text,
524 const blink::WebFindOptions& options,
525 scoped_refptr<extensions::WebviewFindFunction> find_function) {
526 find_helper_.Find(guest_web_contents(), search_text, options, find_function);
529 void WebViewGuest::StopFinding(content::StopFindAction action) {
530 find_helper_.CancelAllFindSessions();
531 guest_web_contents()->StopFinding(action);
534 void WebViewGuest::Go(int relative_index) {
535 guest_web_contents()->GetController().GoToOffset(relative_index);
538 void WebViewGuest::Reload() {
539 // TODO(fsamuel): Don't check for repost because we don't want to show
540 // Chromium's repost warning. We might want to implement a separate API
541 // for registering a callback if a repost is about to happen.
542 guest_web_contents()->GetController().Reload(false);
546 void WebViewGuest::RequestGeolocationPermission(
548 const GURL& requesting_frame,
550 const base::Callback<void(bool)>& callback) {
551 base::DictionaryValue request_info;
552 request_info.Set(guestview::kUrl,
553 base::Value::CreateStringValue(requesting_frame.spec()));
554 request_info.Set(guestview::kUserGesture,
555 base::Value::CreateBooleanValue(user_gesture));
557 // It is safe to hold an unretained pointer to WebViewGuest because this
558 // callback is called from WebViewGuest::SetPermission.
559 const PermissionResponseCallback permission_callback =
560 base::Bind(&WebViewGuest::OnWebViewGeolocationPermissionResponse,
561 base::Unretained(this),
565 int request_id = RequestPermissionInternal(
566 static_cast<BrowserPluginPermissionType>(
567 WEB_VIEW_PERMISSION_TYPE_GEOLOCATION),
570 false /* allowed_by_default */);
571 bridge_id_to_request_id_map_[bridge_id] = request_id;
574 void WebViewGuest::OnWebViewGeolocationPermissionResponse(
577 const base::Callback<void(bool)>& callback,
579 const std::string& user_input) {
580 // The <webview> embedder has allowed the permission. We now need to make sure
581 // that the embedder has geolocation permission.
582 RemoveBridgeID(bridge_id);
584 if (!allow || !attached()) {
589 content::GeolocationPermissionContext* geolocation_context =
590 browser_context()->GetGeolocationPermissionContext();
592 DCHECK(geolocation_context);
593 geolocation_context->RequestGeolocationPermission(
594 embedder_web_contents()->GetRenderProcessHost()->GetID(),
595 embedder_web_contents()->GetRoutingID(),
596 // The geolocation permission request here is not initiated
597 // through WebGeolocationPermissionRequest. We are only interested
598 // in the fact whether the embedder/app has geolocation
599 // permission. Therefore we use an invalid |bridge_id|.
601 embedder_web_contents()->GetLastCommittedURL(),
606 void WebViewGuest::CancelGeolocationPermissionRequest(int bridge_id) {
607 int request_id = RemoveBridgeID(bridge_id);
608 RequestMap::iterator request_itr =
609 pending_permission_requests_.find(request_id);
611 if (request_itr == pending_permission_requests_.end())
614 pending_permission_requests_.erase(request_itr);
617 void WebViewGuest::OnWebViewMediaPermissionResponse(
618 const content::MediaStreamRequest& request,
619 const content::MediaResponseCallback& callback,
621 const std::string& user_input) {
622 if (!allow || !attached()) {
624 callback.Run(content::MediaStreamDevices(),
625 content::MEDIA_DEVICE_INVALID_STATE,
626 scoped_ptr<content::MediaStreamUI>());
629 if (!embedder_web_contents()->GetDelegate())
632 embedder_web_contents()->GetDelegate()->
633 RequestMediaAccessPermission(embedder_web_contents(), request, callback);
636 void WebViewGuest::OnWebViewDownloadPermissionResponse(
637 const base::Callback<void(bool)>& callback,
639 const std::string& user_input) {
640 callback.Run(allow && attached());
643 void WebViewGuest::OnWebViewPointerLockPermissionResponse(
644 const base::Callback<void(bool)>& callback,
646 const std::string& user_input) {
647 callback.Run(allow && attached());
650 WebViewGuest::SetPermissionResult WebViewGuest::SetPermission(
652 PermissionResponseAction action,
653 const std::string& user_input) {
654 RequestMap::iterator request_itr =
655 pending_permission_requests_.find(request_id);
657 if (request_itr == pending_permission_requests_.end())
658 return SET_PERMISSION_INVALID;
660 const PermissionResponseInfo& info = request_itr->second;
661 bool allow = (action == ALLOW) ||
662 ((action == DEFAULT) && info.allowed_by_default);
664 info.callback.Run(allow, user_input);
666 // Only record user initiated (i.e. non-default) actions.
667 if (action != DEFAULT)
668 RecordUserInitiatedUMA(info, allow);
670 pending_permission_requests_.erase(request_itr);
672 return allow ? SET_PERMISSION_ALLOWED : SET_PERMISSION_DENIED;
675 void WebViewGuest::SetUserAgentOverride(
676 const std::string& user_agent_override) {
677 is_overriding_user_agent_ = !user_agent_override.empty();
678 if (is_overriding_user_agent_) {
679 content::RecordAction(UserMetricsAction("WebView.Guest.OverrideUA"));
681 guest_web_contents()->SetUserAgentOverride(user_agent_override);
684 void WebViewGuest::Stop() {
685 guest_web_contents()->Stop();
688 void WebViewGuest::Terminate() {
689 content::RecordAction(UserMetricsAction("WebView.Guest.Terminate"));
690 base::ProcessHandle process_handle =
691 guest_web_contents()->GetRenderProcessHost()->GetHandle();
693 base::KillProcess(process_handle, content::RESULT_CODE_KILLED, false);
696 bool WebViewGuest::ClearData(const base::Time remove_since,
698 const base::Closure& callback) {
699 content::RecordAction(UserMetricsAction("WebView.Guest.ClearData"));
700 content::StoragePartition* partition =
701 content::BrowserContext::GetStoragePartition(
702 guest_web_contents()->GetBrowserContext(),
703 guest_web_contents()->GetSiteInstance());
708 partition->ClearData(
710 content::StoragePartition::QUOTA_MANAGED_STORAGE_MASK_ALL,
712 content::StoragePartition::OriginMatcherFunction(),
719 WebViewGuest::~WebViewGuest() {
722 void WebViewGuest::DidCommitProvisionalLoadForFrame(
724 const base::string16& frame_unique_name,
727 content::PageTransition transition_type,
728 content::RenderViewHost* render_view_host) {
729 find_helper_.CancelAllFindSessions();
731 scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
732 args->SetString(guestview::kUrl, url.spec());
733 args->SetBoolean(guestview::kIsTopLevel, is_main_frame);
734 args->SetInteger(webview::kInternalCurrentEntryIndex,
735 guest_web_contents()->GetController().GetCurrentEntryIndex());
736 args->SetInteger(webview::kInternalEntryCount,
737 guest_web_contents()->GetController().GetEntryCount());
738 args->SetInteger(webview::kInternalProcessId,
739 guest_web_contents()->GetRenderProcessHost()->GetID());
741 new GuestViewBase::Event(webview::kEventLoadCommit, args.Pass()));
743 // Update the current zoom factor for the new page.
744 current_zoom_factor_ = content::ZoomLevelToZoomFactor(
745 guest_web_contents()->GetZoomLevel());
748 chromevox_injected_ = false;
749 main_frame_id_ = frame_id;
753 void WebViewGuest::DidFailProvisionalLoad(
755 const base::string16& frame_unique_name,
757 const GURL& validated_url,
759 const base::string16& error_description,
760 content::RenderViewHost* render_view_host) {
761 // Translate the |error_code| into an error string.
762 std::string error_type;
763 base::RemoveChars(net::ErrorToString(error_code), "net::", &error_type);
764 LoadAbort(is_main_frame, validated_url, error_type);
767 void WebViewGuest::DidStartProvisionalLoadForFrame(
769 int64 parent_frame_id,
771 const GURL& validated_url,
773 bool is_iframe_srcdoc,
774 content::RenderViewHost* render_view_host) {
775 scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
776 args->SetString(guestview::kUrl, validated_url.spec());
777 args->SetBoolean(guestview::kIsTopLevel, is_main_frame);
779 new GuestViewBase::Event(webview::kEventLoadStart, args.Pass()));
782 void WebViewGuest::DocumentLoadedInFrame(
784 content::RenderViewHost* render_view_host) {
785 if (frame_id == main_frame_id_)
786 InjectChromeVoxIfNeeded(render_view_host);
789 void WebViewGuest::DidStopLoading(content::RenderViewHost* render_view_host) {
790 scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
791 DispatchEvent(new GuestViewBase::Event(webview::kEventLoadStop, args.Pass()));
794 void WebViewGuest::WebContentsDestroyed() {
795 // Clean up custom context menu items for this guest.
796 extensions::MenuManager* menu_manager = extensions::MenuManager::Get(
797 Profile::FromBrowserContext(browser_context()));
798 menu_manager->RemoveAllContextItems(extensions::MenuItem::ExtensionKey(
799 embedder_extension_id(), view_instance_id()));
801 RemoveWebViewFromExtensionRendererState(web_contents());
804 void WebViewGuest::UserAgentOverrideSet(const std::string& user_agent) {
805 content::NavigationController& controller =
806 guest_web_contents()->GetController();
807 content::NavigationEntry* entry = controller.GetVisibleEntry();
810 entry->SetIsOverridingUserAgent(!user_agent.empty());
812 // We cannot reload now because all resource loads are suspended until
814 pending_reload_on_attachment_ = true;
817 guest_web_contents()->GetController().Reload(false);
820 void WebViewGuest::LoadHandlerCalled() {
821 scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
823 new GuestViewBase::Event(webview::kEventContentLoad, args.Pass()));
826 void WebViewGuest::LoadRedirect(const GURL& old_url,
829 scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
830 args->SetBoolean(guestview::kIsTopLevel, is_top_level);
831 args->SetString(webview::kNewURL, new_url.spec());
832 args->SetString(webview::kOldURL, old_url.spec());
834 new GuestViewBase::Event(webview::kEventLoadRedirect, args.Pass()));
837 void WebViewGuest::AddWebViewToExtensionRendererState() {
838 const GURL& site_url = guest_web_contents()->GetSiteInstance()->GetSiteURL();
839 std::string partition_domain;
840 std::string partition_id;
842 if (!GetGuestPartitionConfigForSite(
843 site_url, &partition_domain, &partition_id, &in_memory)) {
847 DCHECK(embedder_extension_id() == partition_domain);
849 ExtensionRendererState::WebViewInfo webview_info;
850 webview_info.embedder_process_id = embedder_render_process_id();
851 webview_info.instance_id = view_instance_id();
852 webview_info.partition_id = partition_id;
853 webview_info.embedder_extension_id = embedder_extension_id();
855 content::BrowserThread::PostTask(
856 content::BrowserThread::IO, FROM_HERE,
858 &ExtensionRendererState::AddWebView,
859 base::Unretained(ExtensionRendererState::GetInstance()),
860 guest_web_contents()->GetRenderProcessHost()->GetID(),
861 guest_web_contents()->GetRoutingID(),
866 void WebViewGuest::RemoveWebViewFromExtensionRendererState(
867 WebContents* web_contents) {
868 content::BrowserThread::PostTask(
869 content::BrowserThread::IO, FROM_HERE,
871 &ExtensionRendererState::RemoveWebView,
872 base::Unretained(ExtensionRendererState::GetInstance()),
873 web_contents->GetRenderProcessHost()->GetID(),
874 web_contents->GetRoutingID()));
877 GURL WebViewGuest::ResolveURL(const std::string& src) {
878 if (!in_extension()) {
883 GURL default_url(base::StringPrintf("%s://%s/",
884 extensions::kExtensionScheme,
885 embedder_extension_id().c_str()));
886 return default_url.Resolve(src);
889 void WebViewGuest::SizeChanged(const gfx::Size& old_size,
890 const gfx::Size& new_size) {
891 scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
892 args->SetInteger(webview::kOldHeight, old_size.height());
893 args->SetInteger(webview::kOldWidth, old_size.width());
894 args->SetInteger(webview::kNewHeight, new_size.height());
895 args->SetInteger(webview::kNewWidth, new_size.width());
897 new GuestViewBase::Event(webview::kEventSizeChanged, args.Pass()));
900 void WebViewGuest::RequestMediaAccessPermission(
901 const content::MediaStreamRequest& request,
902 const content::MediaResponseCallback& callback) {
903 base::DictionaryValue request_info;
906 base::Value::CreateStringValue(request.security_origin.spec()));
907 RequestPermission(static_cast<BrowserPluginPermissionType>(
908 WEB_VIEW_PERMISSION_TYPE_MEDIA),
910 base::Bind(&WebViewGuest::OnWebViewMediaPermissionResponse,
911 base::Unretained(this),
914 false /* allowed_by_default */);
917 void WebViewGuest::CanDownload(
918 const std::string& request_method,
920 const base::Callback<void(bool)>& callback) {
921 base::DictionaryValue request_info;
924 base::Value::CreateStringValue(url.spec()));
926 static_cast<BrowserPluginPermissionType>(
927 WEB_VIEW_PERMISSION_TYPE_DOWNLOAD),
929 base::Bind(&WebViewGuest::OnWebViewDownloadPermissionResponse,
930 base::Unretained(this),
932 false /* allowed_by_default */);
935 void WebViewGuest::RequestPointerLockPermission(
937 bool last_unlocked_by_target,
938 const base::Callback<void(bool)>& callback) {
939 base::DictionaryValue request_info;
940 request_info.Set(guestview::kUserGesture,
941 base::Value::CreateBooleanValue(user_gesture));
942 request_info.Set(webview::kLastUnlockedBySelf,
943 base::Value::CreateBooleanValue(last_unlocked_by_target));
944 request_info.Set(guestview::kUrl,
945 base::Value::CreateStringValue(
946 guest_web_contents()->GetLastCommittedURL().spec()));
949 static_cast<BrowserPluginPermissionType>(
950 WEB_VIEW_PERMISSION_TYPE_POINTER_LOCK),
952 base::Bind(&WebViewGuest::OnWebViewPointerLockPermissionResponse,
953 base::Unretained(this),
955 false /* allowed_by_default */);
958 content::JavaScriptDialogManager*
959 WebViewGuest::GetJavaScriptDialogManager() {
960 return &javascript_dialog_helper_;
963 #if defined(OS_CHROMEOS)
964 void WebViewGuest::OnAccessibilityStatusChanged(
965 const chromeos::AccessibilityStatusEventDetails& details) {
966 if (details.notification_type == chromeos::ACCESSIBILITY_MANAGER_SHUTDOWN) {
967 accessibility_subscription_.reset();
968 } else if (details.notification_type ==
969 chromeos::ACCESSIBILITY_TOGGLE_SPOKEN_FEEDBACK) {
971 InjectChromeVoxIfNeeded(guest_web_contents()->GetRenderViewHost());
973 chromevox_injected_ = false;
978 void WebViewGuest::InjectChromeVoxIfNeeded(
979 content::RenderViewHost* render_view_host) {
980 #if defined(OS_CHROMEOS)
981 if (!chromevox_injected_) {
982 chromeos::AccessibilityManager* manager =
983 chromeos::AccessibilityManager::Get();
984 if (manager && manager->IsSpokenFeedbackEnabled()) {
985 manager->InjectChromeVox(render_view_host);
986 chromevox_injected_ = true;
992 int WebViewGuest::RemoveBridgeID(int bridge_id) {
993 std::map<int, int>::iterator bridge_itr =
994 bridge_id_to_request_id_map_.find(bridge_id);
995 if (bridge_itr == bridge_id_to_request_id_map_.end())
996 return webview::kInvalidPermissionRequestID;
998 int request_id = bridge_itr->second;
999 bridge_id_to_request_id_map_.erase(bridge_itr);
1003 int WebViewGuest::RequestPermissionInternal(
1004 BrowserPluginPermissionType permission_type,
1005 const base::DictionaryValue& request_info,
1006 const PermissionResponseCallback& callback,
1007 bool allowed_by_default) {
1008 // If there are too many pending permission requests then reject this request.
1009 if (pending_permission_requests_.size() >=
1010 webview::kMaxOutstandingPermissionRequests) {
1011 // Let the stack unwind before we deny the permission request so that
1012 // objects held by the permission request are not destroyed immediately
1013 // after creation. This is to allow those same objects to be accessed again
1014 // in the same scope without fear of use after freeing.
1015 base::MessageLoop::current()->PostTask(
1017 base::Bind(&PermissionResponseCallback::Run,
1018 base::Owned(new PermissionResponseCallback(callback)),
1021 return webview::kInvalidPermissionRequestID;
1024 int request_id = next_permission_request_id_++;
1025 pending_permission_requests_[request_id] =
1026 PermissionResponseInfo(callback, permission_type, allowed_by_default);
1027 scoped_ptr<base::DictionaryValue> args(request_info.DeepCopy());
1028 args->SetInteger(webview::kRequestId, request_id);
1029 switch (static_cast<int>(permission_type)) {
1030 case BROWSER_PLUGIN_PERMISSION_TYPE_NEW_WINDOW: {
1032 new GuestViewBase::Event(webview::kEventNewWindow, args.Pass()));
1035 case WEB_VIEW_PERMISSION_TYPE_JAVASCRIPT_DIALOG: {
1037 new GuestViewBase::Event(webview::kEventDialog, args.Pass()));
1041 args->SetString(webview::kPermission,
1042 PermissionTypeToString(permission_type));
1043 DispatchEvent(new GuestViewBase::Event(webview::kEventPermissionRequest,
1051 WebViewGuest::PermissionResponseInfo::PermissionResponseInfo()
1052 : permission_type(BROWSER_PLUGIN_PERMISSION_TYPE_UNKNOWN),
1053 allowed_by_default(false) {
1056 WebViewGuest::PermissionResponseInfo::PermissionResponseInfo(
1057 const PermissionResponseCallback& callback,
1058 BrowserPluginPermissionType permission_type,
1059 bool allowed_by_default)
1060 : callback(callback),
1061 permission_type(permission_type),
1062 allowed_by_default(allowed_by_default) {
1065 WebViewGuest::PermissionResponseInfo::~PermissionResponseInfo() {
1068 void WebViewGuest::ShowContextMenu(int request_id,
1069 const MenuItemVector* items) {
1070 if (!pending_menu_.get())
1073 // Make sure this was the correct request.
1074 if (request_id != pending_context_menu_request_id_)
1077 // TODO(lazyboy): Implement.
1080 ContextMenuDelegate* menu_delegate =
1081 ContextMenuDelegate::FromWebContents(guest_web_contents());
1082 menu_delegate->ShowMenu(pending_menu_.Pass());