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/extensions/api/web_request/web_request_api.h"
12 #include "chrome/browser/extensions/api/web_view/web_view_internal_api.h"
13 #include "chrome/browser/extensions/chrome_extension_web_contents_observer.h"
14 #include "chrome/browser/extensions/menu_manager.h"
15 #include "chrome/browser/favicon/favicon_tab_helper.h"
16 #include "chrome/browser/guest_view/web_view/web_view_constants.h"
17 #include "chrome/browser/guest_view/web_view/web_view_permission_helper.h"
18 #include "chrome/browser/guest_view/web_view/web_view_permission_types.h"
19 #include "chrome/browser/guest_view/web_view/web_view_renderer_state.h"
20 #include "chrome/browser/renderer_context_menu/render_view_context_menu.h"
21 #include "chrome/browser/ui/pdf/pdf_tab_helper.h"
22 #include "chrome/browser/ui/zoom/zoom_controller.h"
23 #include "chrome/common/chrome_version_info.h"
24 #include "chrome/common/extensions/chrome_extension_messages.h"
25 #include "chrome/common/render_messages.h"
26 #include "components/renderer_context_menu/context_menu_delegate.h"
27 #include "content/public/browser/browser_thread.h"
28 #include "content/public/browser/child_process_security_policy.h"
29 #include "content/public/browser/native_web_keyboard_event.h"
30 #include "content/public/browser/navigation_entry.h"
31 #include "content/public/browser/notification_details.h"
32 #include "content/public/browser/notification_service.h"
33 #include "content/public/browser/notification_source.h"
34 #include "content/public/browser/notification_types.h"
35 #include "content/public/browser/render_process_host.h"
36 #include "content/public/browser/render_view_host.h"
37 #include "content/public/browser/resource_request_details.h"
38 #include "content/public/browser/site_instance.h"
39 #include "content/public/browser/storage_partition.h"
40 #include "content/public/browser/user_metrics.h"
41 #include "content/public/browser/web_contents.h"
42 #include "content/public/browser/web_contents_delegate.h"
43 #include "content/public/common/media_stream_request.h"
44 #include "content/public/common/page_zoom.h"
45 #include "content/public/common/result_codes.h"
46 #include "content/public/common/stop_find_action.h"
47 #include "content/public/common/url_constants.h"
48 #include "extensions/browser/extension_system.h"
49 #include "extensions/browser/guest_view/guest_view_constants.h"
50 #include "extensions/browser/guest_view/guest_view_manager.h"
51 #include "extensions/common/constants.h"
52 #include "ipc/ipc_message_macros.h"
53 #include "net/base/escape.h"
54 #include "net/base/net_errors.h"
55 #include "third_party/WebKit/public/web/WebFindOptions.h"
56 #include "ui/base/models/simple_menu_model.h"
58 #if defined(ENABLE_PRINTING)
59 #if defined(ENABLE_FULL_PRINTING)
60 #include "chrome/browser/printing/print_preview_message_handler.h"
61 #include "chrome/browser/printing/print_view_manager.h"
63 #include "chrome/browser/printing/print_view_manager_basic.h"
64 #endif // defined(ENABLE_FULL_PRINTING)
65 #endif // defined(ENABLE_PRINTING)
67 #if defined(OS_CHROMEOS)
68 #include "chrome/browser/chromeos/accessibility/accessibility_manager.h"
71 using base::UserMetricsAction;
72 using content::RenderFrameHost;
73 using content::ResourceType;
74 using content::WebContents;
76 namespace extensions {
80 std::string WindowOpenDispositionToString(
81 WindowOpenDisposition window_open_disposition) {
82 switch (window_open_disposition) {
86 return "save_to_disk";
89 case NEW_BACKGROUND_TAB:
90 return "new_background_tab";
91 case NEW_FOREGROUND_TAB:
92 return "new_foreground_tab";
98 NOTREACHED() << "Unknown Window Open Disposition";
103 static std::string TerminationStatusToString(base::TerminationStatus status) {
105 case base::TERMINATION_STATUS_NORMAL_TERMINATION:
107 case base::TERMINATION_STATUS_ABNORMAL_TERMINATION:
108 case base::TERMINATION_STATUS_STILL_RUNNING:
110 case base::TERMINATION_STATUS_PROCESS_WAS_KILLED:
112 case base::TERMINATION_STATUS_PROCESS_CRASHED:
114 case base::TERMINATION_STATUS_MAX_ENUM:
117 NOTREACHED() << "Unknown Termination Status.";
121 std::string GetStoragePartitionIdFromSiteURL(const GURL& site_url) {
122 const std::string& partition_id = site_url.query();
123 bool persist_storage = site_url.path().find("persist") != std::string::npos;
124 return (persist_storage ? webview::kPersistPrefix : "") + partition_id;
127 void RemoveWebViewEventListenersOnIOThread(
129 const std::string& extension_id,
130 int embedder_process_id,
131 int view_instance_id) {
132 DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO));
133 ExtensionWebRequestEventRouter::GetInstance()->RemoveWebViewEventListeners(
140 void ParsePartitionParam(const base::DictionaryValue& create_params,
141 std::string* storage_partition_id,
142 bool* persist_storage) {
143 std::string partition_str;
144 if (!create_params.GetString(webview::kStoragePartitionId, &partition_str)) {
148 // Since the "persist:" prefix is in ASCII, StartsWith will work fine on
149 // UTF-8 encoded |partition_id|. If the prefix is a match, we can safely
150 // remove the prefix without splicing in the middle of a multi-byte codepoint.
151 // We can use the rest of the string as UTF-8 encoded one.
152 if (StartsWithASCII(partition_str, "persist:", true)) {
153 size_t index = partition_str.find(":");
154 CHECK(index != std::string::npos);
155 // It is safe to do index + 1, since we tested for the full prefix above.
156 *storage_partition_id = partition_str.substr(index + 1);
158 if (storage_partition_id->empty()) {
159 // TODO(lazyboy): Better way to deal with this error.
162 *persist_storage = true;
164 *storage_partition_id = partition_str;
165 *persist_storage = false;
172 GuestViewBase* WebViewGuest::Create(content::BrowserContext* browser_context,
173 int guest_instance_id) {
174 return new WebViewGuest(browser_context, guest_instance_id);
178 bool WebViewGuest::GetGuestPartitionConfigForSite(
180 std::string* partition_domain,
181 std::string* partition_name,
183 if (!site.SchemeIs(content::kGuestScheme))
186 // Since guest URLs are only used for packaged apps, there must be an app
188 CHECK(site.has_host());
189 *partition_domain = site.host();
190 // Since persistence is optional, the path must either be empty or the
192 *in_memory = (site.path() != "/persist");
193 // The partition name is user supplied value, which we have encoded when the
194 // URL was created, so it needs to be decoded.
196 net::UnescapeURLComponent(site.query(), net::UnescapeRule::NORMAL);
201 const char WebViewGuest::Type[] = "webview";
204 int WebViewGuest::GetViewInstanceId(WebContents* contents) {
205 WebViewGuest* guest = FromWebContents(contents);
207 return guestview::kInstanceIDNone;
209 return guest->view_instance_id();
213 scoped_ptr<base::ListValue> WebViewGuest::MenuModelToValue(
214 const ui::SimpleMenuModel& menu_model) {
215 scoped_ptr<base::ListValue> items(new base::ListValue());
216 for (int i = 0; i < menu_model.GetItemCount(); ++i) {
217 base::DictionaryValue* item_value = new base::DictionaryValue();
218 // TODO(lazyboy): We need to expose some kind of enum equivalent of
219 // |command_id| instead of plain integers.
220 item_value->SetInteger(webview::kMenuItemCommandId,
221 menu_model.GetCommandIdAt(i));
222 item_value->SetString(webview::kMenuItemLabel, menu_model.GetLabelAt(i));
223 items->Append(item_value);
228 const char* WebViewGuest::GetAPINamespace() {
229 return webview::kAPINamespace;
232 void WebViewGuest::CreateWebContents(
233 const std::string& embedder_extension_id,
234 int embedder_render_process_id,
235 const base::DictionaryValue& create_params,
236 const WebContentsCreatedCallback& callback) {
237 content::RenderProcessHost* embedder_render_process_host =
238 content::RenderProcessHost::FromID(embedder_render_process_id);
239 std::string storage_partition_id;
240 bool persist_storage = false;
241 std::string storage_partition_string;
242 ParsePartitionParam(create_params, &storage_partition_id, &persist_storage);
243 // Validate that the partition id coming from the renderer is valid UTF-8,
244 // since we depend on this in other parts of the code, such as FilePath
245 // creation. If the validation fails, treat it as a bad message and kill the
247 if (!base::IsStringUTF8(storage_partition_id)) {
248 content::RecordAction(
249 base::UserMetricsAction("BadMessageTerminate_BPGM"));
251 embedder_render_process_host->GetHandle(),
252 content::RESULT_CODE_KILLED_BAD_MESSAGE, false);
256 std::string url_encoded_partition = net::EscapeQueryParamValue(
257 storage_partition_id, false);
258 // The SiteInstance of a given webview tag is based on the fact that it's
259 // a guest process in addition to which platform application the tag
260 // belongs to and what storage partition is in use, rather than the URL
261 // that the tag is being navigated to.
262 GURL guest_site(base::StringPrintf("%s://%s/%s?%s",
263 content::kGuestScheme,
264 embedder_extension_id.c_str(),
265 persist_storage ? "persist" : "",
266 url_encoded_partition.c_str()));
268 // If we already have a webview tag in the same app using the same storage
269 // partition, we should use the same SiteInstance so the existing tag and
270 // the new tag can script each other.
271 GuestViewManager* guest_view_manager =
272 GuestViewManager::FromBrowserContext(
273 embedder_render_process_host->GetBrowserContext());
274 content::SiteInstance* guest_site_instance =
275 guest_view_manager->GetGuestSiteInstance(guest_site);
276 if (!guest_site_instance) {
277 // Create the SiteInstance in a new BrowsingInstance, which will ensure
278 // that webview tags are also not allowed to send messages across
279 // different partitions.
280 guest_site_instance = content::SiteInstance::CreateForURL(
281 embedder_render_process_host->GetBrowserContext(), guest_site);
283 WebContents::CreateParams params(
284 embedder_render_process_host->GetBrowserContext(),
285 guest_site_instance);
286 params.guest_delegate = this;
287 callback.Run(WebContents::Create(params));
290 void WebViewGuest::DidAttachToEmbedder() {
294 if (extra_params()->GetString(webview::kName, &name)) {
295 // If the guest window's name is empty, then the WebView tag's name is
296 // assigned. Otherwise, the guest window's name takes precedence over the
297 // WebView tag's name.
301 ReportFrameNameChange(name_);
303 std::string user_agent_override;
304 if (extra_params()->GetString(webview::kParameterUserAgentOverride,
305 &user_agent_override)) {
306 SetUserAgentOverride(user_agent_override);
308 SetUserAgentOverride("");
312 if (extra_params()->GetString("src", &src) && !src.empty())
316 // We need to do a navigation here if the target URL has changed between
317 // the time the WebContents was created and the time it was attached.
318 // We also need to do an initial navigation if a RenderView was never
319 // created for the new window in cases where there is no referrer.
320 PendingWindowMap::iterator it =
321 GetOpener()->pending_new_windows_.find(this);
322 if (it != GetOpener()->pending_new_windows_.end()) {
323 const NewWindowInfo& new_window_info = it->second;
324 if (new_window_info.changed || !guest_web_contents()->HasOpener())
325 NavigateGuest(new_window_info.url.spec());
330 // Once a new guest is attached to the DOM of the embedder page, then the
331 // lifetime of the new guest is no longer managed by the opener guest.
332 GetOpener()->pending_new_windows_.erase(this);
335 ZoomController* zoom_controller = ZoomController::FromWebContents(
336 embedder_web_contents());
337 if (!zoom_controller)
339 // Listen to the embedder's zoom changes.
340 zoom_controller->AddObserver(this);
341 // Set the guest's initial zoom level to be equal to the embedder's.
342 ZoomController::FromWebContents(guest_web_contents())->
343 SetZoomLevel(zoom_controller->GetZoomLevel());
346 void WebViewGuest::DidInitialize() {
347 script_executor_.reset(
348 new ScriptExecutor(guest_web_contents(), &script_observers_));
350 notification_registrar_.Add(
351 this, content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME,
352 content::Source<WebContents>(guest_web_contents()));
354 notification_registrar_.Add(
355 this, content::NOTIFICATION_RESOURCE_RECEIVED_REDIRECT,
356 content::Source<WebContents>(guest_web_contents()));
358 #if defined(OS_CHROMEOS)
359 chromeos::AccessibilityManager* accessibility_manager =
360 chromeos::AccessibilityManager::Get();
361 CHECK(accessibility_manager);
362 accessibility_subscription_ = accessibility_manager->RegisterCallback(
363 base::Bind(&WebViewGuest::OnAccessibilityStatusChanged,
364 base::Unretained(this)));
367 AttachWebViewHelpers(guest_web_contents());
370 void WebViewGuest::AttachWebViewHelpers(WebContents* contents) {
371 // Create a zoom controller for the guest contents give it access to
372 // GetZoomLevel() and and SetZoomLevel() in WebViewGuest.
373 // TODO(wjmaclean) This currently uses the same HostZoomMap as the browser
374 // context, but we eventually want to isolate the guest contents from zoom
375 // changes outside the guest (e.g. in the main browser), so we should
376 // create a separate HostZoomMap for the guest.
377 ZoomController::CreateForWebContents(contents);
379 FaviconTabHelper::CreateForWebContents(contents);
380 ChromeExtensionWebContentsObserver::CreateForWebContents(contents);
381 #if defined(ENABLE_PRINTING)
382 #if defined(ENABLE_FULL_PRINTING)
383 printing::PrintViewManager::CreateForWebContents(contents);
384 printing::PrintPreviewMessageHandler::CreateForWebContents(contents);
386 printing::PrintViewManagerBasic::CreateForWebContents(contents);
387 #endif // defined(ENABLE_FULL_PRINTING)
388 #endif // defined(ENABLE_PRINTING)
389 PDFTabHelper::CreateForWebContents(contents);
390 web_view_permission_helper_.reset(new WebViewPermissionHelper(this));
393 void WebViewGuest::DidStopLoading() {
394 scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
395 DispatchEventToEmbedder(
396 new GuestViewBase::Event(webview::kEventLoadStop, args.Pass()));
399 void WebViewGuest::EmbedderDestroyed() {
400 // TODO(fsamuel): WebRequest event listeners for <webview> should survive
401 // reparenting of a <webview> within a single embedder. Right now, we keep
402 // around the browser state for the listener for the lifetime of the embedder.
403 // Ideally, the lifetime of the listeners should match the lifetime of the
404 // <webview> DOM node. Once http://crbug.com/156219 is resolved we can move
405 // the call to RemoveWebViewEventListenersOnIOThread back to
406 // WebViewGuest::WebContentsDestroyed.
407 content::BrowserThread::PostTask(
408 content::BrowserThread::IO,
411 &RemoveWebViewEventListenersOnIOThread,
412 browser_context(), embedder_extension_id(),
413 embedder_render_process_id(),
414 view_instance_id()));
417 void WebViewGuest::GuestDestroyed() {
418 // Clean up custom context menu items for this guest.
419 MenuManager* menu_manager = MenuManager::Get(
420 Profile::FromBrowserContext(browser_context()));
421 menu_manager->RemoveAllContextItems(MenuItem::ExtensionKey(
422 embedder_extension_id(), view_instance_id()));
424 RemoveWebViewStateFromIOThread(web_contents());
427 void WebViewGuest::GuestReady() {
428 // The guest RenderView should always live in an isolated guest process.
429 CHECK(guest_web_contents()->GetRenderProcessHost()->IsIsolatedGuest());
430 Send(new ChromeViewMsg_SetName(guest_web_contents()->GetRoutingID(), name_));
433 void WebViewGuest::GuestSizeChangedDueToAutoSize(const gfx::Size& old_size,
434 const gfx::Size& new_size) {
435 scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
436 args->SetInteger(webview::kOldHeight, old_size.height());
437 args->SetInteger(webview::kOldWidth, old_size.width());
438 args->SetInteger(webview::kNewHeight, new_size.height());
439 args->SetInteger(webview::kNewWidth, new_size.width());
440 DispatchEventToEmbedder(
441 new GuestViewBase::Event(webview::kEventSizeChanged, args.Pass()));
444 bool WebViewGuest::IsAutoSizeSupported() const {
448 bool WebViewGuest::IsDragAndDropEnabled() const {
452 void WebViewGuest::WillDestroy() {
453 if (!attached() && GetOpener())
454 GetOpener()->pending_new_windows_.erase(this);
455 DestroyUnattachedWindows();
458 bool WebViewGuest::AddMessageToConsole(WebContents* source,
460 const base::string16& message,
462 const base::string16& source_id) {
463 scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
464 // Log levels are from base/logging.h: LogSeverity.
465 args->SetInteger(webview::kLevel, level);
466 args->SetString(webview::kMessage, message);
467 args->SetInteger(webview::kLine, line_no);
468 args->SetString(webview::kSourceId, source_id);
469 DispatchEventToEmbedder(
470 new GuestViewBase::Event(webview::kEventConsoleMessage, args.Pass()));
474 void WebViewGuest::CloseContents(WebContents* source) {
475 scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
476 DispatchEventToEmbedder(
477 new GuestViewBase::Event(webview::kEventClose, args.Pass()));
480 void WebViewGuest::FindReply(WebContents* source,
482 int number_of_matches,
483 const gfx::Rect& selection_rect,
484 int active_match_ordinal,
486 find_helper_.FindReply(request_id, number_of_matches, selection_rect,
487 active_match_ordinal, final_update);
490 bool WebViewGuest::HandleContextMenu(
491 const content::ContextMenuParams& params) {
492 ContextMenuDelegate* menu_delegate =
493 ContextMenuDelegate::FromWebContents(guest_web_contents());
494 DCHECK(menu_delegate);
496 pending_menu_ = menu_delegate->BuildMenu(guest_web_contents(), params);
498 // Pass it to embedder.
499 int request_id = ++pending_context_menu_request_id_;
500 scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
501 scoped_ptr<base::ListValue> items =
502 MenuModelToValue(pending_menu_->menu_model());
503 args->Set(webview::kContextMenuItems, items.release());
504 args->SetInteger(webview::kRequestId, request_id);
505 DispatchEventToEmbedder(
506 new GuestViewBase::Event(webview::kEventContextMenu, args.Pass()));
510 void WebViewGuest::HandleKeyboardEvent(
512 const content::NativeWebKeyboardEvent& event) {
516 if (HandleKeyboardShortcuts(event))
519 // Send the unhandled keyboard events back to the embedder to reprocess them.
520 // TODO(fsamuel): This introduces the possibility of out-of-order keyboard
521 // events because the guest may be arbitrarily delayed when responding to
522 // keyboard events. In that time, the embedder may have received and processed
523 // additional key events. This needs to be fixed as soon as possible.
524 // See http://crbug.com/229882.
525 embedder_web_contents()->GetDelegate()->HandleKeyboardEvent(
526 web_contents(), event);
529 void WebViewGuest::LoadProgressChanged(content::WebContents* source,
531 scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
532 args->SetString(guestview::kUrl, guest_web_contents()->GetURL().spec());
533 args->SetDouble(webview::kProgress, progress);
534 DispatchEventToEmbedder(
535 new GuestViewBase::Event(webview::kEventLoadProgress, args.Pass()));
538 void WebViewGuest::LoadAbort(bool is_top_level,
540 const std::string& error_type) {
541 scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
542 args->SetBoolean(guestview::kIsTopLevel, is_top_level);
543 args->SetString(guestview::kUrl, url.possibly_invalid_spec());
544 args->SetString(guestview::kReason, error_type);
545 DispatchEventToEmbedder(
546 new GuestViewBase::Event(webview::kEventLoadAbort, args.Pass()));
549 void WebViewGuest::OnUpdateFrameName(bool is_top_level,
550 const std::string& name) {
557 ReportFrameNameChange(name);
560 void WebViewGuest::CreateNewGuestWebViewWindow(
561 const content::OpenURLParams& params) {
562 GuestViewManager* guest_manager =
563 GuestViewManager::FromBrowserContext(browser_context());
564 // Set the attach params to use the same partition as the opener.
565 // We pull the partition information from the site's URL, which is of the
566 // form guest://site/{persist}?{partition_name}.
567 const GURL& site_url = guest_web_contents()->GetSiteInstance()->GetSiteURL();
568 const std::string storage_partition_id =
569 GetStoragePartitionIdFromSiteURL(site_url);
570 base::DictionaryValue create_params;
571 create_params.SetString(webview::kStoragePartitionId, storage_partition_id);
573 guest_manager->CreateGuest(WebViewGuest::Type,
574 embedder_extension_id(),
575 embedder_web_contents(),
577 base::Bind(&WebViewGuest::NewGuestWebViewCallback,
578 base::Unretained(this),
582 void WebViewGuest::NewGuestWebViewCallback(
583 const content::OpenURLParams& params,
584 content::WebContents* guest_web_contents) {
585 WebViewGuest* new_guest = WebViewGuest::FromWebContents(guest_web_contents);
586 new_guest->SetOpener(this);
588 // Take ownership of |new_guest|.
589 pending_new_windows_.insert(
590 std::make_pair(new_guest, NewWindowInfo(params.url, std::string())));
592 // Request permission to show the new window.
593 RequestNewWindowPermission(params.disposition, gfx::Rect(),
595 new_guest->guest_web_contents());
598 // TODO(fsamuel): Find a reliable way to test the 'responsive' and
599 // 'unresponsive' events.
600 void WebViewGuest::RendererResponsive(content::WebContents* source) {
601 scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
602 args->SetInteger(webview::kProcessId,
603 guest_web_contents()->GetRenderProcessHost()->GetID());
604 DispatchEventToEmbedder(
605 new GuestViewBase::Event(webview::kEventResponsive, args.Pass()));
608 void WebViewGuest::RendererUnresponsive(content::WebContents* source) {
609 scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
610 args->SetInteger(webview::kProcessId,
611 guest_web_contents()->GetRenderProcessHost()->GetID());
612 DispatchEventToEmbedder(
613 new GuestViewBase::Event(webview::kEventUnresponsive, args.Pass()));
616 void WebViewGuest::Observe(int type,
617 const content::NotificationSource& source,
618 const content::NotificationDetails& details) {
620 case content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME: {
621 DCHECK_EQ(content::Source<WebContents>(source).ptr(),
622 guest_web_contents());
623 if (content::Source<WebContents>(source).ptr() == guest_web_contents())
627 case content::NOTIFICATION_RESOURCE_RECEIVED_REDIRECT: {
628 DCHECK_EQ(content::Source<WebContents>(source).ptr(),
629 guest_web_contents());
630 content::ResourceRedirectDetails* resource_redirect_details =
631 content::Details<content::ResourceRedirectDetails>(details).ptr();
632 bool is_top_level = resource_redirect_details->resource_type ==
633 content::RESOURCE_TYPE_MAIN_FRAME;
634 LoadRedirect(resource_redirect_details->url,
635 resource_redirect_details->new_url,
640 NOTREACHED() << "Unexpected notification sent.";
645 double WebViewGuest::GetZoom() {
646 return current_zoom_factor_;
649 void WebViewGuest::Find(
650 const base::string16& search_text,
651 const blink::WebFindOptions& options,
652 scoped_refptr<WebViewInternalFindFunction> find_function) {
653 find_helper_.Find(guest_web_contents(), search_text, options, find_function);
656 void WebViewGuest::StopFinding(content::StopFindAction action) {
657 find_helper_.CancelAllFindSessions();
658 guest_web_contents()->StopFinding(action);
661 void WebViewGuest::Go(int relative_index) {
662 guest_web_contents()->GetController().GoToOffset(relative_index);
665 void WebViewGuest::Reload() {
666 // TODO(fsamuel): Don't check for repost because we don't want to show
667 // Chromium's repost warning. We might want to implement a separate API
668 // for registering a callback if a repost is about to happen.
669 guest_web_contents()->GetController().Reload(false);
672 void WebViewGuest::SetUserAgentOverride(
673 const std::string& user_agent_override) {
676 is_overriding_user_agent_ = !user_agent_override.empty();
677 if (is_overriding_user_agent_) {
678 content::RecordAction(UserMetricsAction("WebView.Guest.OverrideUA"));
680 guest_web_contents()->SetUserAgentOverride(user_agent_override);
683 void WebViewGuest::Stop() {
684 guest_web_contents()->Stop();
687 void WebViewGuest::Terminate() {
688 content::RecordAction(UserMetricsAction("WebView.Guest.Terminate"));
689 base::ProcessHandle process_handle =
690 guest_web_contents()->GetRenderProcessHost()->GetHandle();
692 base::KillProcess(process_handle, content::RESULT_CODE_KILLED, false);
695 bool WebViewGuest::ClearData(const base::Time remove_since,
697 const base::Closure& callback) {
698 content::RecordAction(UserMetricsAction("WebView.Guest.ClearData"));
699 content::StoragePartition* partition =
700 content::BrowserContext::GetStoragePartition(
701 guest_web_contents()->GetBrowserContext(),
702 guest_web_contents()->GetSiteInstance());
707 partition->ClearData(
709 content::StoragePartition::QUOTA_MANAGED_STORAGE_MASK_ALL,
711 content::StoragePartition::OriginMatcherFunction(),
718 WebViewGuest::WebViewGuest(content::BrowserContext* browser_context,
719 int guest_instance_id)
720 : GuestView<WebViewGuest>(browser_context, guest_instance_id),
721 pending_context_menu_request_id_(0),
722 is_overriding_user_agent_(false),
723 chromevox_injected_(false),
724 current_zoom_factor_(1.0),
726 javascript_dialog_helper_(this) {
729 WebViewGuest::~WebViewGuest() {
732 void WebViewGuest::DidCommitProvisionalLoadForFrame(
733 content::RenderFrameHost* render_frame_host,
735 content::PageTransition transition_type) {
736 find_helper_.CancelAllFindSessions();
738 scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
739 args->SetString(guestview::kUrl, url.spec());
740 args->SetBoolean(guestview::kIsTopLevel, !render_frame_host->GetParent());
741 args->SetInteger(webview::kInternalCurrentEntryIndex,
742 guest_web_contents()->GetController().GetCurrentEntryIndex());
743 args->SetInteger(webview::kInternalEntryCount,
744 guest_web_contents()->GetController().GetEntryCount());
745 args->SetInteger(webview::kInternalProcessId,
746 guest_web_contents()->GetRenderProcessHost()->GetID());
747 DispatchEventToEmbedder(
748 new GuestViewBase::Event(webview::kEventLoadCommit, args.Pass()));
750 // Update the current zoom factor for the new page.
751 ZoomController* zoom_controller =
752 ZoomController::FromWebContents(guest_web_contents());
753 DCHECK(zoom_controller);
754 current_zoom_factor_ = zoom_controller->GetZoomLevel();
756 if (!render_frame_host->GetParent())
757 chromevox_injected_ = false;
760 void WebViewGuest::DidFailProvisionalLoad(
761 content::RenderFrameHost* render_frame_host,
762 const GURL& validated_url,
764 const base::string16& error_description) {
765 LoadAbort(!render_frame_host->GetParent(), validated_url,
766 net::ErrorToShortString(error_code));
769 void WebViewGuest::DidStartProvisionalLoadForFrame(
770 content::RenderFrameHost* render_frame_host,
771 const GURL& validated_url,
773 bool is_iframe_srcdoc) {
774 scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
775 args->SetString(guestview::kUrl, validated_url.spec());
776 args->SetBoolean(guestview::kIsTopLevel, !render_frame_host->GetParent());
777 DispatchEventToEmbedder(
778 new GuestViewBase::Event(webview::kEventLoadStart, args.Pass()));
781 void WebViewGuest::DocumentLoadedInFrame(
782 content::RenderFrameHost* render_frame_host) {
783 if (!render_frame_host->GetParent())
784 InjectChromeVoxIfNeeded(render_frame_host->GetRenderViewHost());
787 bool WebViewGuest::OnMessageReceived(const IPC::Message& message,
788 RenderFrameHost* render_frame_host) {
790 IPC_BEGIN_MESSAGE_MAP(WebViewGuest, message)
791 IPC_MESSAGE_HANDLER(ChromeViewHostMsg_UpdateFrameName, OnUpdateFrameName)
792 IPC_MESSAGE_UNHANDLED(handled = false)
793 IPC_END_MESSAGE_MAP()
797 void WebViewGuest::RenderProcessGone(base::TerminationStatus status) {
798 // Cancel all find sessions in progress.
799 find_helper_.CancelAllFindSessions();
801 scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
802 args->SetInteger(webview::kProcessId,
803 guest_web_contents()->GetRenderProcessHost()->GetID());
804 args->SetString(webview::kReason, TerminationStatusToString(status));
805 DispatchEventToEmbedder(
806 new GuestViewBase::Event(webview::kEventExit, args.Pass()));
809 void WebViewGuest::UserAgentOverrideSet(const std::string& user_agent) {
812 content::NavigationController& controller =
813 guest_web_contents()->GetController();
814 content::NavigationEntry* entry = controller.GetVisibleEntry();
817 entry->SetIsOverridingUserAgent(!user_agent.empty());
818 guest_web_contents()->GetController().Reload(false);
821 void WebViewGuest::ReportFrameNameChange(const std::string& name) {
823 scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
824 args->SetString(webview::kName, name);
825 DispatchEventToEmbedder(
826 new GuestViewBase::Event(webview::kEventFrameNameChanged, args.Pass()));
829 void WebViewGuest::LoadHandlerCalled() {
830 scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
831 DispatchEventToEmbedder(
832 new GuestViewBase::Event(webview::kEventContentLoad, args.Pass()));
835 void WebViewGuest::LoadRedirect(const GURL& old_url,
838 scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
839 args->SetBoolean(guestview::kIsTopLevel, is_top_level);
840 args->SetString(webview::kNewURL, new_url.spec());
841 args->SetString(webview::kOldURL, old_url.spec());
842 DispatchEventToEmbedder(
843 new GuestViewBase::Event(webview::kEventLoadRedirect, args.Pass()));
846 void WebViewGuest::PushWebViewStateToIOThread() {
847 const GURL& site_url = guest_web_contents()->GetSiteInstance()->GetSiteURL();
848 std::string partition_domain;
849 std::string partition_id;
851 if (!GetGuestPartitionConfigForSite(
852 site_url, &partition_domain, &partition_id, &in_memory)) {
856 DCHECK(embedder_extension_id() == partition_domain);
858 WebViewRendererState::WebViewInfo web_view_info;
859 web_view_info.embedder_process_id = embedder_render_process_id();
860 web_view_info.instance_id = view_instance_id();
861 web_view_info.partition_id = partition_id;
862 web_view_info.embedder_extension_id = embedder_extension_id();
864 content::BrowserThread::PostTask(
865 content::BrowserThread::IO,
867 base::Bind(&WebViewRendererState::AddGuest,
868 base::Unretained(WebViewRendererState::GetInstance()),
869 guest_web_contents()->GetRenderProcessHost()->GetID(),
870 guest_web_contents()->GetRoutingID(),
875 void WebViewGuest::RemoveWebViewStateFromIOThread(
876 WebContents* web_contents) {
877 content::BrowserThread::PostTask(
878 content::BrowserThread::IO, FROM_HERE,
880 &WebViewRendererState::RemoveGuest,
881 base::Unretained(WebViewRendererState::GetInstance()),
882 web_contents->GetRenderProcessHost()->GetID(),
883 web_contents->GetRoutingID()));
886 content::WebContents* WebViewGuest::CreateNewGuestWindow(
887 const content::WebContents::CreateParams& create_params) {
888 GuestViewManager* guest_manager =
889 GuestViewManager::FromBrowserContext(browser_context());
890 return guest_manager->CreateGuestWithWebContentsParams(
892 embedder_extension_id(),
893 embedder_web_contents()->GetRenderProcessHost()->GetID(),
897 void WebViewGuest::RequestMediaAccessPermission(
898 content::WebContents* source,
899 const content::MediaStreamRequest& request,
900 const content::MediaResponseCallback& callback) {
901 web_view_permission_helper_->RequestMediaAccessPermission(source,
906 void WebViewGuest::CanDownload(
907 content::RenderViewHost* render_view_host,
909 const std::string& request_method,
910 const base::Callback<void(bool)>& callback) {
911 web_view_permission_helper_->CanDownload(render_view_host,
917 void WebViewGuest::RequestPointerLockPermission(
919 bool last_unlocked_by_target,
920 const base::Callback<void(bool)>& callback) {
921 web_view_permission_helper_->RequestPointerLockPermission(
923 last_unlocked_by_target,
927 void WebViewGuest::WillAttachToEmbedder() {
928 // We must install the mapping from guests to WebViews prior to resuming
929 // suspended resource loads so that the WebRequest API will catch resource
931 PushWebViewStateToIOThread();
934 content::JavaScriptDialogManager*
935 WebViewGuest::GetJavaScriptDialogManager() {
936 return &javascript_dialog_helper_;
939 content::ColorChooser* WebViewGuest::OpenColorChooser(
940 WebContents* web_contents,
942 const std::vector<content::ColorSuggestion>& suggestions) {
943 if (!attached() || !embedder_web_contents()->GetDelegate())
945 return embedder_web_contents()->GetDelegate()->OpenColorChooser(
946 web_contents, color, suggestions);
949 void WebViewGuest::RunFileChooser(WebContents* web_contents,
950 const content::FileChooserParams& params) {
951 if (!attached() || !embedder_web_contents()->GetDelegate())
954 embedder_web_contents()->GetDelegate()->RunFileChooser(web_contents, params);
957 void WebViewGuest::NavigateGuest(const std::string& src) {
958 GURL url = ResolveURL(src);
960 // Do not allow navigating a guest to schemes other than known safe schemes.
961 // This will block the embedder trying to load unwanted schemes, e.g.
962 // chrome://settings.
963 bool scheme_is_blocked =
964 (!content::ChildProcessSecurityPolicy::GetInstance()->IsWebSafeScheme(
966 !url.SchemeIs(url::kAboutScheme)) ||
967 url.SchemeIs(url::kJavaScriptScheme);
968 if (scheme_is_blocked || !url.is_valid()) {
969 LoadAbort(true /* is_top_level */, url,
970 net::ErrorToShortString(net::ERR_ABORTED));
974 GURL validated_url(url);
975 guest_web_contents()->GetRenderProcessHost()->
976 FilterURL(false, &validated_url);
977 // As guests do not swap processes on navigation, only navigations to
978 // normal web URLs are supported. No protocol handlers are installed for
979 // other schemes (e.g., WebUI or extensions), and no permissions or bindings
980 // can be granted to the guest process.
981 LoadURLWithParams(validated_url,
983 content::PAGE_TRANSITION_AUTO_TOPLEVEL,
984 guest_web_contents());
987 #if defined(OS_CHROMEOS)
988 void WebViewGuest::OnAccessibilityStatusChanged(
989 const chromeos::AccessibilityStatusEventDetails& details) {
990 if (details.notification_type == chromeos::ACCESSIBILITY_MANAGER_SHUTDOWN) {
991 accessibility_subscription_.reset();
992 } else if (details.notification_type ==
993 chromeos::ACCESSIBILITY_TOGGLE_SPOKEN_FEEDBACK) {
995 InjectChromeVoxIfNeeded(guest_web_contents()->GetRenderViewHost());
997 chromevox_injected_ = false;
1002 void WebViewGuest::InjectChromeVoxIfNeeded(
1003 content::RenderViewHost* render_view_host) {
1004 #if defined(OS_CHROMEOS)
1005 if (!chromevox_injected_) {
1006 chromeos::AccessibilityManager* manager =
1007 chromeos::AccessibilityManager::Get();
1008 if (manager && manager->IsSpokenFeedbackEnabled()) {
1009 manager->InjectChromeVox(render_view_host);
1010 chromevox_injected_ = true;
1016 bool WebViewGuest::HandleKeyboardShortcuts(
1017 const content::NativeWebKeyboardEvent& event) {
1018 if (event.type != blink::WebInputEvent::RawKeyDown)
1021 // If the user hits the escape key without any modifiers then unlock the
1022 // mouse if necessary.
1023 if ((event.windowsKeyCode == ui::VKEY_ESCAPE) &&
1024 !(event.modifiers & blink::WebInputEvent::InputModifiers)) {
1025 return guest_web_contents()->GotResponseToLockMouseRequest(false);
1028 #if defined(OS_MACOSX)
1029 if (event.modifiers != blink::WebInputEvent::MetaKey)
1032 if (event.windowsKeyCode == ui::VKEY_OEM_4) {
1037 if (event.windowsKeyCode == ui::VKEY_OEM_6) {
1042 if (event.windowsKeyCode == ui::VKEY_BROWSER_BACK) {
1047 if (event.windowsKeyCode == ui::VKEY_BROWSER_FORWARD) {
1056 void WebViewGuest::SetUpAutoSize() {
1057 // Read the autosize parameters passed in from the embedder.
1058 bool auto_size_enabled = false;
1059 extra_params()->GetBoolean(webview::kAttributeAutoSize, &auto_size_enabled);
1063 extra_params()->GetInteger(webview::kAttributeMaxHeight, &max_height);
1064 extra_params()->GetInteger(webview::kAttributeMaxWidth, &max_width);
1068 extra_params()->GetInteger(webview::kAttributeMinHeight, &min_height);
1069 extra_params()->GetInteger(webview::kAttributeMinWidth, &min_width);
1071 // Call SetAutoSize to apply all the appropriate validation and clipping of
1073 SetAutoSize(auto_size_enabled,
1074 gfx::Size(min_width, min_height),
1075 gfx::Size(max_width, max_height));
1078 void WebViewGuest::ShowContextMenu(int request_id,
1079 const MenuItemVector* items) {
1080 if (!pending_menu_.get())
1083 // Make sure this was the correct request.
1084 if (request_id != pending_context_menu_request_id_)
1087 // TODO(lazyboy): Implement.
1090 ContextMenuDelegate* menu_delegate =
1091 ContextMenuDelegate::FromWebContents(guest_web_contents());
1092 menu_delegate->ShowMenu(pending_menu_.Pass());
1095 void WebViewGuest::SetName(const std::string& name) {
1100 Send(new ChromeViewMsg_SetName(routing_id(), name_));
1103 void WebViewGuest::SetZoom(double zoom_factor) {
1104 ZoomController* zoom_controller =
1105 ZoomController::FromWebContents(guest_web_contents());
1106 DCHECK(zoom_controller);
1107 double zoom_level = content::ZoomFactorToZoomLevel(zoom_factor);
1108 zoom_controller->SetZoomLevel(zoom_level);
1110 scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
1111 args->SetDouble(webview::kOldZoomFactor, current_zoom_factor_);
1112 args->SetDouble(webview::kNewZoomFactor, zoom_factor);
1113 DispatchEventToEmbedder(
1114 new GuestViewBase::Event(webview::kEventZoomChange, args.Pass()));
1116 current_zoom_factor_ = zoom_factor;
1119 void WebViewGuest::AddNewContents(content::WebContents* source,
1120 content::WebContents* new_contents,
1121 WindowOpenDisposition disposition,
1122 const gfx::Rect& initial_pos,
1124 bool* was_blocked) {
1126 *was_blocked = false;
1127 RequestNewWindowPermission(disposition,
1133 content::WebContents* WebViewGuest::OpenURLFromTab(
1134 content::WebContents* source,
1135 const content::OpenURLParams& params) {
1136 // If the guest wishes to navigate away prior to attachment then we save the
1137 // navigation to perform upon attachment. Navigation initializes a lot of
1138 // state that assumes an embedder exists, such as RenderWidgetHostViewGuest.
1139 // Navigation also resumes resource loading which we don't want to allow
1140 // until attachment.
1142 WebViewGuest* opener = GetOpener();
1143 PendingWindowMap::iterator it =
1144 opener->pending_new_windows_.find(this);
1145 if (it == opener->pending_new_windows_.end())
1147 const NewWindowInfo& info = it->second;
1148 NewWindowInfo new_window_info(params.url, info.name);
1149 new_window_info.changed = new_window_info.url != info.url;
1150 it->second = new_window_info;
1153 if (params.disposition == CURRENT_TAB) {
1154 // This can happen for cross-site redirects.
1155 LoadURLWithParams(params.url, params.referrer, params.transition, source);
1159 CreateNewGuestWebViewWindow(params);
1163 void WebViewGuest::WebContentsCreated(WebContents* source_contents,
1164 int opener_render_frame_id,
1165 const base::string16& frame_name,
1166 const GURL& target_url,
1167 content::WebContents* new_contents) {
1168 WebViewGuest* guest = WebViewGuest::FromWebContents(new_contents);
1170 guest->SetOpener(this);
1171 std::string guest_name = base::UTF16ToUTF8(frame_name);
1172 guest->name_ = guest_name;
1173 pending_new_windows_.insert(
1174 std::make_pair(guest, NewWindowInfo(target_url, guest_name)));
1177 void WebViewGuest::LoadURLWithParams(const GURL& url,
1178 const content::Referrer& referrer,
1179 content::PageTransition transition_type,
1180 content::WebContents* web_contents) {
1181 content::NavigationController::LoadURLParams load_url_params(url);
1182 load_url_params.referrer = referrer;
1183 load_url_params.transition_type = transition_type;
1184 load_url_params.extra_headers = std::string();
1185 if (is_overriding_user_agent_) {
1186 load_url_params.override_user_agent =
1187 content::NavigationController::UA_OVERRIDE_TRUE;
1189 web_contents->GetController().LoadURLWithParams(load_url_params);
1192 void WebViewGuest::RequestNewWindowPermission(
1193 WindowOpenDisposition disposition,
1194 const gfx::Rect& initial_bounds,
1196 content::WebContents* new_contents) {
1197 WebViewGuest* guest = WebViewGuest::FromWebContents(new_contents);
1200 PendingWindowMap::iterator it = pending_new_windows_.find(guest);
1201 if (it == pending_new_windows_.end())
1203 const NewWindowInfo& new_window_info = it->second;
1205 // Retrieve the opener partition info if we have it.
1206 const GURL& site_url = new_contents->GetSiteInstance()->GetSiteURL();
1207 std::string storage_partition_id = GetStoragePartitionIdFromSiteURL(site_url);
1209 base::DictionaryValue request_info;
1210 request_info.SetInteger(webview::kInitialHeight, initial_bounds.height());
1211 request_info.SetInteger(webview::kInitialWidth, initial_bounds.width());
1212 request_info.Set(webview::kTargetURL,
1213 new base::StringValue(new_window_info.url.spec()));
1214 request_info.Set(webview::kName, new base::StringValue(new_window_info.name));
1215 request_info.SetInteger(webview::kWindowID, guest->GetGuestInstanceID());
1216 // We pass in partition info so that window-s created through newwindow
1217 // API can use it to set their partition attribute.
1218 request_info.Set(webview::kStoragePartitionId,
1219 new base::StringValue(storage_partition_id));
1221 webview::kWindowOpenDisposition,
1222 new base::StringValue(WindowOpenDispositionToString(disposition)));
1224 web_view_permission_helper_->
1225 RequestPermission(WEB_VIEW_PERMISSION_TYPE_NEW_WINDOW,
1227 base::Bind(&WebViewGuest::OnWebViewNewWindowResponse,
1228 base::Unretained(this),
1229 guest->GetGuestInstanceID()),
1230 false /* allowed_by_default */);
1233 void WebViewGuest::DestroyUnattachedWindows() {
1234 // Destroy() reaches in and removes the WebViewGuest from its opener's
1235 // pending_new_windows_ set. To avoid mutating the set while iterating, we
1236 // create a copy of the pending new windows set and iterate over the copy.
1237 PendingWindowMap pending_new_windows(pending_new_windows_);
1238 // Clean up unattached new windows opened by this guest.
1239 for (PendingWindowMap::const_iterator it = pending_new_windows.begin();
1240 it != pending_new_windows.end(); ++it) {
1241 it->first->Destroy();
1243 // All pending windows should be removed from the set after Destroy() is
1244 // called on all of them.
1245 DCHECK(pending_new_windows_.empty());
1248 GURL WebViewGuest::ResolveURL(const std::string& src) {
1249 if (!in_extension()) {
1254 GURL default_url(base::StringPrintf("%s://%s/",
1256 embedder_extension_id().c_str()));
1257 return default_url.Resolve(src);
1260 void WebViewGuest::OnWebViewNewWindowResponse(
1261 int new_window_instance_id,
1263 const std::string& user_input) {
1264 WebViewGuest* guest =
1265 WebViewGuest::From(embedder_render_process_id(), new_window_instance_id);
1273 void WebViewGuest::OnZoomChanged(
1274 const ZoomController::ZoomChangedEventData& data) {
1275 ZoomController::FromWebContents(guest_web_contents())->
1276 SetZoomLevel(data.new_zoom_level);
1279 } // namespace extensions