1 // Copyright (c) 2014 GitHub, Inc.
2 // Use of this source code is governed by the MIT license that can be
3 // found in the LICENSE file.
5 #include "atom/browser/api/atom_api_web_contents.h"
11 #include "atom/browser/api/atom_api_debugger.h"
12 #include "atom/browser/api/atom_api_session.h"
13 #include "atom/browser/api/atom_api_window.h"
14 #include "atom/browser/atom_browser_client.h"
15 #include "atom/browser/atom_browser_context.h"
16 #include "atom/browser/atom_browser_main_parts.h"
17 #include "atom/browser/lib/bluetooth_chooser.h"
18 #include "atom/browser/native_window.h"
19 #include "atom/browser/net/atom_network_delegate.h"
20 #include "atom/browser/osr/osr_output_device.h"
21 #include "atom/browser/osr/osr_render_widget_host_view.h"
22 #include "atom/browser/osr/osr_web_contents_view.h"
23 #include "atom/browser/ui/drag_util.h"
24 #include "atom/browser/web_contents_permission_helper.h"
25 #include "atom/browser/web_contents_preferences.h"
26 #include "atom/browser/web_contents_zoom_controller.h"
27 #include "atom/browser/web_view_guest_delegate.h"
28 #include "atom/common/api/api_messages.h"
29 #include "atom/common/api/event_emitter_caller.h"
30 #include "atom/common/color_util.h"
31 #include "atom/common/mouse_util.h"
32 #include "atom/common/native_mate_converters/blink_converter.h"
33 #include "atom/common/native_mate_converters/callback.h"
34 #include "atom/common/native_mate_converters/content_converter.h"
35 #include "atom/common/native_mate_converters/file_path_converter.h"
36 #include "atom/common/native_mate_converters/gfx_converter.h"
37 #include "atom/common/native_mate_converters/gurl_converter.h"
38 #include "atom/common/native_mate_converters/image_converter.h"
39 #include "atom/common/native_mate_converters/net_converter.h"
40 #include "atom/common/native_mate_converters/string16_converter.h"
41 #include "atom/common/native_mate_converters/value_converter.h"
42 #include "atom/common/options_switches.h"
43 #include "base/strings/utf_string_conversions.h"
44 #include "base/threading/thread_task_runner_handle.h"
45 #include "brightray/browser/inspectable_web_contents.h"
46 #include "brightray/browser/inspectable_web_contents_view.h"
47 #include "chrome/browser/printing/print_preview_message_handler.h"
48 #include "chrome/browser/printing/print_view_manager_basic.h"
49 #include "chrome/browser/ssl/security_state_tab_helper.h"
50 #include "content/browser/frame_host/navigation_entry_impl.h"
51 #include "content/browser/renderer_host/render_widget_host_impl.h"
52 #include "content/browser/web_contents/web_contents_impl.h"
53 #include "content/common/view_messages.h"
54 #include "content/public/browser/favicon_status.h"
55 #include "content/public/browser/native_web_keyboard_event.h"
56 #include "content/public/browser/navigation_details.h"
57 #include "content/public/browser/navigation_entry.h"
58 #include "content/public/browser/navigation_handle.h"
59 #include "content/public/browser/notification_details.h"
60 #include "content/public/browser/notification_source.h"
61 #include "content/public/browser/notification_types.h"
62 #include "content/public/browser/plugin_service.h"
63 #include "content/public/browser/render_frame_host.h"
64 #include "content/public/browser/render_process_host.h"
65 #include "content/public/browser/render_view_host.h"
66 #include "content/public/browser/render_widget_host.h"
67 #include "content/public/browser/render_widget_host_view.h"
68 #include "content/public/browser/resource_request_details.h"
69 #include "content/public/browser/service_worker_context.h"
70 #include "content/public/browser/site_instance.h"
71 #include "content/public/browser/storage_partition.h"
72 #include "content/public/browser/web_contents.h"
73 #include "content/public/common/context_menu_params.h"
74 #include "native_mate/dictionary.h"
75 #include "native_mate/object_template_builder.h"
76 #include "net/url_request/url_request_context.h"
77 #include "third_party/WebKit/public/platform/WebInputEvent.h"
78 #include "third_party/WebKit/public/web/WebFindOptions.h"
79 #include "ui/display/screen.h"
82 #include "tizen/extensions/common/xwalk_extension_server.h"
85 #if !defined(OS_MACOSX) && !defined(USE_EFL)
86 #include "ui/aura/window.h"
89 #include "atom/common/node_includes.h"
93 struct PrintSettings {
95 bool print_background;
103 struct Converter<atom::SetSizeParams> {
104 static bool FromV8(v8::Isolate* isolate,
105 v8::Local<v8::Value> val,
106 atom::SetSizeParams* out) {
107 mate::Dictionary params;
108 if (!ConvertFromV8(isolate, val, ¶ms))
111 if (params.Get("enableAutoSize", &autosize))
112 out->enable_auto_size.reset(new bool(true));
114 if (params.Get("min", &size))
115 out->min_size.reset(new gfx::Size(size));
116 if (params.Get("max", &size))
117 out->max_size.reset(new gfx::Size(size));
118 if (params.Get("normal", &size))
119 out->normal_size.reset(new gfx::Size(size));
125 struct Converter<PrintSettings> {
126 static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val,
127 PrintSettings* out) {
128 mate::Dictionary dict;
129 if (!ConvertFromV8(isolate, val, &dict))
131 dict.Get("silent", &(out->silent));
132 dict.Get("printBackground", &(out->print_background));
138 struct Converter<WindowOpenDisposition> {
139 static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
140 WindowOpenDisposition val) {
141 std::string disposition = "other";
143 case WindowOpenDisposition::CURRENT_TAB:
144 disposition = "default";
146 case WindowOpenDisposition::NEW_FOREGROUND_TAB:
147 disposition = "foreground-tab";
149 case WindowOpenDisposition::NEW_BACKGROUND_TAB:
150 disposition = "background-tab";
152 case WindowOpenDisposition::NEW_POPUP:
153 case WindowOpenDisposition::NEW_WINDOW:
154 disposition = "new-window";
156 case WindowOpenDisposition::SAVE_TO_DISK:
157 disposition = "save-to-disk";
162 return mate::ConvertToV8(isolate, disposition);
167 struct Converter<content::SavePageType> {
168 static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val,
169 content::SavePageType* out) {
170 std::string save_type;
171 if (!ConvertFromV8(isolate, val, &save_type))
173 save_type = base::ToLowerASCII(save_type);
174 if (save_type == "htmlonly") {
175 *out = content::SAVE_PAGE_TYPE_AS_ONLY_HTML;
176 } else if (save_type == "htmlcomplete") {
177 *out = content::SAVE_PAGE_TYPE_AS_COMPLETE_HTML;
178 } else if (save_type == "mhtml") {
179 *out = content::SAVE_PAGE_TYPE_AS_MHTML;
188 struct Converter<atom::api::WebContents::Type> {
189 static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
190 atom::api::WebContents::Type val) {
191 using Type = atom::api::WebContents::Type;
192 std::string type = "";
194 case Type::BACKGROUND_PAGE: type = "backgroundPage"; break;
195 case Type::BROWSER_WINDOW: type = "window"; break;
196 case Type::BROWSER_VIEW: type = "browserView"; break;
197 case Type::REMOTE: type = "remote"; break;
198 case Type::WEB_VIEW: type = "webview"; break;
199 case Type::OFF_SCREEN: type = "offscreen"; break;
202 return mate::ConvertToV8(isolate, type);
205 static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val,
206 atom::api::WebContents::Type* out) {
207 using Type = atom::api::WebContents::Type;
209 if (!ConvertFromV8(isolate, val, &type))
211 if (type == "backgroundPage") {
212 *out = Type::BACKGROUND_PAGE;
213 } else if (type == "browserView") {
214 *out = Type::BROWSER_VIEW;
215 } else if (type == "webview") {
216 *out = Type::WEB_VIEW;
217 } else if (type == "offscreen") {
218 *out = Type::OFF_SCREEN;
235 content::ServiceWorkerContext* GetServiceWorkerContext(
236 const content::WebContents* web_contents) {
237 auto context = web_contents->GetBrowserContext();
238 auto site_instance = web_contents->GetSiteInstance();
239 if (!context || !site_instance)
242 auto storage_partition =
243 content::BrowserContext::GetStoragePartition(context, site_instance);
244 if (!storage_partition)
247 return storage_partition->GetServiceWorkerContext();
250 // Called when CapturePage is done.
251 void OnCapturePageDone(const base::Callback<void(const gfx::Image&)>& callback,
252 const SkBitmap& bitmap,
253 content::ReadbackResponse response) {
254 callback.Run(gfx::Image::CreateFrom1xBitmap(bitmap));
257 // Set the background color of RenderWidgetHostView.
258 void SetBackgroundColor(content::WebContents* web_contents) {
259 const auto view = web_contents->GetRenderWidgetHostView();
261 WebContentsPreferences* web_preferences =
262 WebContentsPreferences::FromWebContents(web_contents);
263 std::string color_name;
264 if (web_preferences->web_preferences()->GetString(options::kBackgroundColor,
266 view->SetBackgroundColor(ParseHexColor(color_name));
268 view->SetBackgroundColor(SK_ColorTRANSPARENT);
275 WebContents::WebContents(v8::Isolate* isolate,
276 content::WebContents* web_contents,
278 : content::WebContentsObserver(web_contents),
280 zoom_controller_(nullptr),
283 background_throttling_(true),
284 enable_devtools_(true) {
285 if (type == REMOTE) {
286 web_contents->SetUserAgentOverride(GetBrowserContext()->GetUserAgent());
288 AttachAsUserData(web_contents);
290 const mate::Dictionary options = mate::Dictionary::CreateEmpty(isolate);
291 auto session = Session::CreateFrom(isolate, GetBrowserContext());
292 session_.Reset(isolate, session.ToV8());
293 InitWithSessionAndOptions(isolate, web_contents, session, options);
297 WebContents::WebContents(v8::Isolate* isolate, const mate::Dictionary& options)
298 : embedder_(nullptr),
299 zoom_controller_(nullptr),
300 type_(BROWSER_WINDOW),
302 background_throttling_(true),
303 enable_devtools_(true) {
305 options.Get("backgroundThrottling", &background_throttling_);
307 // FIXME(zcbenz): We should read "type" parameter for better design, but
308 // on Windows we have encountered a compiler bug that if we read "type"
309 // from |options| and then set |type_|, a memory corruption will happen
310 // and Electron will soon crash.
311 // Remvoe this after we upgraded to use VS 2015 Update 3.
313 if (options.Get("isGuest", &b) && b)
315 else if (options.Get("isBackgroundPage", &b) && b)
316 type_ = BACKGROUND_PAGE;
317 else if (options.Get("isBrowserView", &b) && b)
318 type_ = BROWSER_VIEW;
319 else if (options.Get("offscreen", &b) && b)
322 // Whether to enable DevTools.
323 options.Get("devTools", &enable_devtools_);
325 // Obtain the session.
326 std::string partition;
327 mate::Handle<api::Session> session;
328 if (options.Get("session", &session)) {
329 } else if (options.Get("partition", &partition)) {
330 session = Session::FromPartition(isolate, partition);
332 // Use the default session if not specified.
333 session = Session::FromPartition(isolate, "");
335 session_.Reset(isolate, session.ToV8());
337 content::WebContents* web_contents;
339 scoped_refptr<content::SiteInstance> site_instance =
340 content::SiteInstance::CreateForURL(
341 session->browser_context(), GURL("chrome-guest://fake-host"));
342 content::WebContents::CreateParams params(
343 session->browser_context(), site_instance);
344 guest_delegate_.reset(new WebViewGuestDelegate);
345 params.guest_delegate = guest_delegate_.get();
346 web_contents = content::WebContents::Create(params);
347 } else if (IsOffScreen()) {
348 bool transparent = false;
349 options.Get("transparent", &transparent);
351 content::WebContents::CreateParams params(session->browser_context());
352 auto* view = new OffScreenWebContentsView(
353 transparent, base::Bind(&WebContents::OnPaint, base::Unretained(this)));
355 params.delegate_view = view;
357 web_contents = content::WebContents::Create(params);
358 view->SetWebContents(web_contents);
360 content::WebContents::CreateParams params(session->browser_context());
361 web_contents = content::WebContents::Create(params);
364 InitWithSessionAndOptions(isolate, web_contents, session, options);
367 void WebContents::InitWithSessionAndOptions(v8::Isolate* isolate,
368 content::WebContents *web_contents,
369 mate::Handle<api::Session> session,
370 const mate::Dictionary& options) {
371 content::WebContentsObserver::Observe(web_contents);
372 InitWithWebContents(web_contents, session->browser_context());
374 managed_web_contents()->GetView()->SetDelegate(this);
376 // Save the preferences in C++.
377 new WebContentsPreferences(web_contents, options);
379 // Initialize permission helper.
380 WebContentsPermissionHelper::CreateForWebContents(web_contents);
381 // Initialize security state client.
382 SecurityStateTabHelper::CreateForWebContents(web_contents);
383 // Initialize zoom controller.
384 WebContentsZoomController::CreateForWebContents(web_contents);
385 zoom_controller_ = WebContentsZoomController::FromWebContents(web_contents);
387 if (options.Get(options::kZoomFactor, &zoom_factor))
388 zoom_controller_->SetDefaultZoomFactor(zoom_factor);
390 web_contents->SetUserAgentOverride(GetBrowserContext()->GetUserAgent());
393 guest_delegate_->Initialize(this);
395 NativeWindow* owner_window = nullptr;
396 if (options.Get("embedder", &embedder_) && embedder_) {
397 // New WebContents's owner_window is the embedder's owner_window.
399 NativeWindowRelay::FromWebContents(embedder_->web_contents());
401 owner_window = relay->window.get();
404 SetOwnerWindow(owner_window);
407 const content::NavigationController* controller =
408 &web_contents->GetController();
409 registrar_.Add(this, content::NOTIFICATION_NAV_ENTRY_PENDING,
410 content::Source<content::NavigationController>(controller));
413 AttachAsUserData(web_contents);
416 WebContents::~WebContents() {
417 // The destroy() is called.
418 if (managed_web_contents()) {
419 // For webview we need to tell content module to do some cleanup work before
421 if (type_ == WEB_VIEW)
422 guest_delegate_->Destroy();
424 RenderViewDeleted(web_contents()->GetRenderViewHost());
425 DestroyWebContents();
429 void WebContents::DestroyWebContents() {
430 // This event is only for internal use, which is emitted when WebContents is
432 Emit("will-destroy");
433 ResetManagedWebContents();
436 bool WebContents::DidAddMessageToConsole(content::WebContents* source,
438 const base::string16& message,
440 const base::string16& source_id) {
441 if (type_ == BROWSER_WINDOW || type_ == OFF_SCREEN) {
442 LOG(ERROR) << "Console Message : " << message << ", source:" << source_id << " (" << line_no << ")";
445 Emit("console-message", level, message, line_no, source_id);
450 void WebContents::OnCreateWindow(
451 const GURL& target_url,
452 const std::string& frame_name,
453 WindowOpenDisposition disposition,
454 const std::vector<std::string>& features,
455 const scoped_refptr<content::ResourceRequestBodyImpl>& body) {
456 if (type_ == BROWSER_WINDOW || type_ == OFF_SCREEN)
457 Emit("-new-window", target_url, frame_name, disposition, features, body);
459 Emit("new-window", target_url, frame_name, disposition, features);
462 void WebContents::WebContentsCreated(content::WebContents* source_contents,
463 int opener_render_process_id,
464 int opener_render_frame_id,
465 const std::string& frame_name,
466 const GURL& target_url,
467 content::WebContents* new_contents) {
468 v8::Locker locker(isolate());
469 v8::HandleScope handle_scope(isolate());
470 auto api_web_contents = CreateFrom(isolate(), new_contents, BROWSER_WINDOW);
471 Emit("-web-contents-created", api_web_contents, target_url, frame_name);
474 void WebContents::AddNewContents(content::WebContents* source,
475 content::WebContents* new_contents,
476 WindowOpenDisposition disposition,
477 const gfx::Rect& initial_rect,
480 v8::Locker locker(isolate());
481 v8::HandleScope handle_scope(isolate());
482 auto api_web_contents = CreateFrom(isolate(), new_contents);
483 if (Emit("-add-new-contents", api_web_contents, disposition, user_gesture,
484 initial_rect.x(), initial_rect.y(), initial_rect.width(),
485 initial_rect.height())) {
486 api_web_contents->DestroyWebContents();
490 content::WebContents* WebContents::OpenURLFromTab(
491 content::WebContents* source,
492 const content::OpenURLParams& params) {
493 if (params.disposition != WindowOpenDisposition::CURRENT_TAB) {
494 if (type_ == BROWSER_WINDOW || type_ == OFF_SCREEN)
495 Emit("-new-window", params.url, "", params.disposition);
497 Emit("new-window", params.url, "", params.disposition);
501 // Give user a chance to cancel navigation.
502 if (Emit("will-navigate", params.url))
505 // Don't load the URL if the web contents was marked as destroyed from a
506 // will-navigate event listener
510 return CommonWebContentsDelegate::OpenURLFromTab(source, params);
513 void WebContents::BeforeUnloadFired(content::WebContents* tab,
515 bool* proceed_to_fire_unload) {
516 if (type_ == BROWSER_WINDOW || type_ == OFF_SCREEN)
517 *proceed_to_fire_unload = proceed;
519 *proceed_to_fire_unload = true;
522 void WebContents::MoveContents(content::WebContents* source,
523 const gfx::Rect& pos) {
527 void WebContents::CloseContents(content::WebContents* source) {
530 if ((type_ == BROWSER_WINDOW || type_ == OFF_SCREEN) && owner_window())
531 owner_window()->CloseContents(source);
534 void WebContents::ActivateContents(content::WebContents* source) {
538 void WebContents::UpdateTargetURL(content::WebContents* source,
540 Emit("update-target-url", url);
543 bool WebContents::IsPopupOrPanel(const content::WebContents* source) const {
544 return type_ == BROWSER_WINDOW;
547 void WebContents::HandleKeyboardEvent(
548 content::WebContents* source,
549 const content::NativeWebKeyboardEvent& event) {
550 if (type_ == WEB_VIEW && embedder_) {
551 // Send the unhandled keyboard events back to the embedder.
552 embedder_->HandleKeyboardEvent(source, event);
554 // Go to the default keyboard handling.
555 CommonWebContentsDelegate::HandleKeyboardEvent(source, event);
559 bool WebContents::PreHandleKeyboardEvent(
560 content::WebContents* source,
561 const content::NativeWebKeyboardEvent& event,
562 bool* is_keyboard_shortcut) {
563 if (event.type == blink::WebInputEvent::Type::RawKeyDown
564 || event.type == blink::WebInputEvent::Type::KeyUp)
565 return Emit("before-input-event", event);
570 void WebContents::EnterFullscreenModeForTab(content::WebContents* source,
571 const GURL& origin) {
572 auto permission_helper =
573 WebContentsPermissionHelper::FromWebContents(source);
574 auto callback = base::Bind(&WebContents::OnEnterFullscreenModeForTab,
575 base::Unretained(this), source, origin);
576 permission_helper->RequestFullscreenPermission(callback);
579 void WebContents::OnEnterFullscreenModeForTab(content::WebContents* source,
584 CommonWebContentsDelegate::EnterFullscreenModeForTab(source, origin);
585 Emit("enter-html-full-screen");
588 void WebContents::ExitFullscreenModeForTab(content::WebContents* source) {
589 CommonWebContentsDelegate::ExitFullscreenModeForTab(source);
590 Emit("leave-html-full-screen");
593 void WebContents::RendererUnresponsive(
594 content::WebContents* source,
595 const content::WebContentsUnresponsiveState& unresponsive_state) {
596 Emit("unresponsive");
597 if ((type_ == BROWSER_WINDOW || type_ == OFF_SCREEN) && owner_window())
598 owner_window()->RendererUnresponsive(source);
601 void WebContents::RendererResponsive(content::WebContents* source) {
603 if ((type_ == BROWSER_WINDOW || type_ == OFF_SCREEN) && owner_window())
604 owner_window()->RendererResponsive(source);
607 bool WebContents::HandleContextMenu(const content::ContextMenuParams& params) {
608 if (params.custom_context.is_pepper_menu) {
609 Emit("pepper-context-menu", std::make_pair(params, web_contents()));
610 web_contents()->NotifyContextMenuClosed(params.custom_context);
612 Emit("context-menu", std::make_pair(params, web_contents()));
618 bool WebContents::OnGoToEntryOffset(int offset) {
623 void WebContents::FindReply(content::WebContents* web_contents,
625 int number_of_matches,
626 const gfx::Rect& selection_rect,
627 int active_match_ordinal,
632 v8::Locker locker(isolate());
633 v8::HandleScope handle_scope(isolate());
634 mate::Dictionary result = mate::Dictionary::CreateEmpty(isolate());
635 result.Set("requestId", request_id);
636 result.Set("matches", number_of_matches);
637 result.Set("selectionArea", selection_rect);
638 result.Set("activeMatchOrdinal", active_match_ordinal);
639 result.Set("finalUpdate", final_update); // Deprecate after 2.0
640 Emit("found-in-page", result);
643 bool WebContents::CheckMediaAccessPermission(
644 content::WebContents* web_contents,
645 const GURL& security_origin,
646 content::MediaStreamType type) {
650 void WebContents::RequestMediaAccessPermission(
651 content::WebContents* web_contents,
652 const content::MediaStreamRequest& request,
653 const content::MediaResponseCallback& callback) {
654 auto permission_helper =
655 WebContentsPermissionHelper::FromWebContents(web_contents);
656 permission_helper->RequestMediaAccessPermission(request, callback);
659 void WebContents::RequestToLockMouse(
660 content::WebContents* web_contents,
662 bool last_unlocked_by_target) {
663 auto permission_helper =
664 WebContentsPermissionHelper::FromWebContents(web_contents);
665 permission_helper->RequestPointerLockPermission(user_gesture);
668 std::unique_ptr<content::BluetoothChooser> WebContents::RunBluetoothChooser(
669 content::RenderFrameHost* frame,
670 const content::BluetoothChooser::EventHandler& event_handler) {
671 std::unique_ptr<BluetoothChooser> bluetooth_chooser(
672 new BluetoothChooser(this, event_handler));
673 return std::move(bluetooth_chooser);
676 void WebContents::BeforeUnloadFired(const base::TimeTicks& proceed_time) {
677 // Do nothing, we override this method just to avoid compilation error since
678 // there are two virtual functions named BeforeUnloadFired.
681 void WebContents::RenderViewCreated(content::RenderViewHost* render_view_host) {
682 const auto impl = content::RenderWidgetHostImpl::FromID(
683 render_view_host->GetProcess()->GetID(),
684 render_view_host->GetRoutingID());
686 impl->disable_hidden_ = !background_throttling_;
689 void WebContents::RenderViewDeleted(content::RenderViewHost* render_view_host) {
690 Emit("render-view-deleted", render_view_host->GetProcess()->GetID());
693 void WebContents::RenderProcessGone(base::TerminationStatus status) {
694 Emit("crashed", status == base::TERMINATION_STATUS_PROCESS_WAS_KILLED);
697 void WebContents::PluginCrashed(const base::FilePath& plugin_path,
698 base::ProcessId plugin_pid) {
699 content::WebPluginInfo info;
700 auto plugin_service = content::PluginService::GetInstance();
701 plugin_service->GetPluginInfoByPath(plugin_path, &info);
702 Emit("plugin-crashed", info.name, info.version);
705 void WebContents::MediaStartedPlaying(const MediaPlayerInfo& video_type,
706 const MediaPlayerId& id) {
707 Emit("media-started-playing");
710 void WebContents::MediaStoppedPlaying(const MediaPlayerInfo& video_type,
711 const MediaPlayerId& id) {
712 Emit("media-paused");
715 void WebContents::DidChangeThemeColor(SkColor theme_color) {
716 Emit("did-change-theme-color", atom::ToRGBHex(theme_color));
719 void WebContents::DocumentLoadedInFrame(
720 content::RenderFrameHost* render_frame_host) {
721 if (!render_frame_host->GetParent())
725 void WebContents::DidFinishLoad(content::RenderFrameHost* render_frame_host,
726 const GURL& validated_url) {
727 bool is_main_frame = !render_frame_host->GetParent();
728 Emit("did-frame-finish-load", is_main_frame);
731 Emit("did-finish-load");
734 void WebContents::DidFailLoad(content::RenderFrameHost* render_frame_host,
737 const base::string16& error_description,
738 bool was_ignored_by_handler) {
739 bool is_main_frame = !render_frame_host->GetParent();
740 Emit("did-fail-load", error_code, error_description, url, is_main_frame);
743 void WebContents::DidStartLoading() {
744 Emit("did-start-loading");
747 void WebContents::DidStopLoading() {
748 Emit("did-stop-loading");
751 void WebContents::DidGetResourceResponseStart(
752 const content::ResourceRequestDetails& details) {
753 Emit("did-get-response-details",
754 details.socket_address.IsEmpty(),
756 details.original_url,
757 details.http_response_code,
760 details.headers.get(),
761 ResourceTypeToString(details.resource_type));
764 void WebContents::DidGetRedirectForResourceRequest(
765 const content::ResourceRedirectDetails& details) {
766 Emit("did-get-redirect-request",
769 (details.resource_type == content::RESOURCE_TYPE_MAIN_FRAME),
770 details.http_response_code,
773 details.headers.get());
776 void WebContents::DidStartNavigation(
777 content::NavigationHandle* navigation_handle) {
778 if (!navigation_handle->IsInMainFrame() || navigation_handle->IsSamePage())
781 if (deferred_load_url_.id) {
782 auto web_contents = navigation_handle->GetWebContents();
783 auto& controller = web_contents->GetController();
784 int id = controller.GetPendingEntry()->GetUniqueID();
785 if (id == deferred_load_url_.id) {
786 if (!deferred_load_url_.params.url.is_empty()) {
787 auto params = deferred_load_url_.params;
788 deferred_load_url_.id = 0;
789 deferred_load_url_.params =
790 content::NavigationController::LoadURLParams(GURL());
791 controller.LoadURLWithParams(params);
792 SetBackgroundColor(web_contents);
794 deferred_load_url_.id = 0;
800 void WebContents::DidFinishNavigation(
801 content::NavigationHandle* navigation_handle) {
802 bool is_main_frame = navigation_handle->IsInMainFrame();
803 if (navigation_handle->HasCommitted() && !navigation_handle->IsErrorPage()) {
804 auto url = navigation_handle->GetURL();
805 bool is_in_page = navigation_handle->IsSamePage();
806 if (is_main_frame && !is_in_page) {
807 Emit("did-navigate", url);
808 } else if (is_in_page) {
809 Emit("did-navigate-in-page", url, is_main_frame);
812 auto url = navigation_handle->GetURL();
813 int code = navigation_handle->GetNetErrorCode();
814 auto description = net::ErrorToShortString(code);
815 Emit("did-fail-provisional-load", code, description, url, is_main_frame);
817 // Do not emit "did-fail-load" for canceled requests.
818 if (code != net::ERR_ABORTED)
819 Emit("did-fail-load", code, description, url, is_main_frame);
823 void WebContents::TitleWasSet(content::NavigationEntry* entry,
826 Emit("-page-title-updated", entry->GetTitle(), explicit_set);
828 Emit("-page-title-updated", "", explicit_set);
831 void WebContents::DidUpdateFaviconURL(
832 const std::vector<content::FaviconURL>& urls) {
833 std::set<GURL> unique_urls;
834 for (const auto& iter : urls) {
835 if (iter.icon_type != content::FaviconURL::FAVICON)
837 const GURL& url = iter.icon_url;
839 unique_urls.insert(url);
841 Emit("page-favicon-updated", unique_urls);
844 void WebContents::Observe(int type,
845 const content::NotificationSource& source,
846 const content::NotificationDetails& details) {
848 case content::NOTIFICATION_NAV_ENTRY_PENDING: {
849 content::NavigationEntry* entry =
850 content::Details<content::NavigationEntry>(details).ptr();
851 content::NavigationEntryImpl* entry_impl =
852 static_cast<content::NavigationEntryImpl*>(entry);
853 // In NavigatorImpl::DidStartMainFrameNavigation when there is no
854 // browser side pending entry available it creates a new one based
855 // on existing pending entry, hence we track the unique id here
856 // instead in WebContents::LoadURL with controller.GetPendingEntry()
857 // TODO(deepak1556): Remove once we have
858 // https://codereview.chromium.org/2661743002.
859 if (entry_impl->frame_tree_node_id() == -1) {
860 deferred_load_url_.id = entry->GetUniqueID();
870 void WebContents::DevToolsReloadPage() {
871 Emit("devtools-reload-page");
874 void WebContents::DevToolsFocused() {
875 Emit("devtools-focused");
878 void WebContents::DevToolsOpened() {
879 v8::Locker locker(isolate());
880 v8::HandleScope handle_scope(isolate());
881 auto handle = WebContents::CreateFrom(
882 isolate(), managed_web_contents()->GetDevToolsWebContents());
883 devtools_web_contents_.Reset(isolate(), handle.ToV8());
885 // Set inspected tabID.
886 base::FundamentalValue tab_id(ID());
887 managed_web_contents()->CallClientFunction(
888 "DevToolsAPI.setInspectedTabId", &tab_id, nullptr, nullptr);
890 // Inherit owner window in devtools.
892 handle->SetOwnerWindow(managed_web_contents()->GetDevToolsWebContents(),
895 Emit("devtools-opened");
898 void WebContents::DevToolsClosed() {
899 v8::Locker locker(isolate());
900 v8::HandleScope handle_scope(isolate());
901 devtools_web_contents_.Reset();
903 Emit("devtools-closed");
906 void WebContents::OnWrtPluginMessage(const Wrt_Message_Data& data) {
907 Wrt_Message_Data tmp = data;
908 HandleWrtPluginMessage(&tmp);
911 void WebContents::OnWrtPluginSyncMessage(const Wrt_Message_Data& data,
912 IPC::Message* reply) {
913 Wrt_Message_Data tmp = data;
914 HandleWrtPluginMessage(&tmp);
915 EwkHostMsg_WrtSyncMessage::WriteReplyParams(reply, tmp.value);
919 void WebContents::HandleWrtPluginMessage(Wrt_Message_Data* msg) {
920 Eina_Stringshare* msg_type = msg->GetType();
922 #define TYPE_BEGIN(x) (!strncmp(msg_type, x, strlen(x)))
923 #define TYPE_IS(x) (!strcmp(msg_type, x))
925 if (TYPE_BEGIN("xwalk://")) {
926 auto extension_server = extensions::XWalkExtensionServer::GetInstance();
927 extension_server->HandleIPCMessage(msg);
929 // implement in future
933 bool WebContents::OnMessageReceived(const IPC::Message& message) {
935 IPC_BEGIN_MESSAGE_MAP(WebContents, message)
936 IPC_MESSAGE_HANDLER(AtomViewHostMsg_Message, OnRendererMessage)
937 IPC_MESSAGE_HANDLER_DELAY_REPLY(AtomViewHostMsg_Message_Sync,
938 OnRendererMessageSync)
939 IPC_MESSAGE_HANDLER_DELAY_REPLY(AtomViewHostMsg_SetTemporaryZoomLevel,
940 OnSetTemporaryZoomLevel)
941 IPC_MESSAGE_HANDLER_DELAY_REPLY(AtomViewHostMsg_GetZoomLevel,
943 IPC_MESSAGE_HANDLER(EwkHostMsg_WrtMessage, OnWrtPluginMessage)
944 IPC_MESSAGE_HANDLER_DELAY_REPLY(EwkHostMsg_WrtSyncMessage, OnWrtPluginSyncMessage)
945 // FIXME: Disable OnCursorChange due to stach_chk_fail crash.
946 // IPC_MESSAGE_HANDLER_CODE(ViewHostMsg_SetCursor, OnCursorChange,
948 IPC_MESSAGE_UNHANDLED(handled = false)
949 IPC_END_MESSAGE_MAP()
954 // There are three ways of destroying a webContents:
955 // 1. call webContents.destroy();
956 // 2. garbage collection;
957 // 3. user closes the window of webContents;
958 // For webview only #1 will happen, for BrowserWindow both #1 and #3 may
959 // happen. The #2 should never happen for webContents, because webview is
960 // managed by GuestViewManager, and BrowserWindow's webContents is managed
962 // For #1, the destructor will do the cleanup work and we only need to make
963 // sure "destroyed" event is emitted. For #3, the content::WebContents will
964 // be destroyed on close, and WebContentsDestroyed would be called for it, so
965 // we need to make sure the api::WebContents is also deleted.
966 void WebContents::WebContentsDestroyed() {
967 // Cleanup relationships with other parts.
970 // We can not call Destroy here because we need to call Emit first, but we
971 // also do not want any method to be used, so just mark as destroyed here.
976 // Destroy the native class in next tick.
977 base::ThreadTaskRunnerHandle::Get()->PostTask(
978 FROM_HERE, GetDestroyClosure());
981 void WebContents::NavigationEntryCommitted(
982 const content::LoadCommittedDetails& details) {
983 Emit("navigation-entry-commited", details.entry->GetURL(),
984 details.is_in_page, details.did_replace_entry);
987 int64_t WebContents::GetID() const {
988 int64_t process_id = web_contents()->GetRenderProcessHost()->GetID();
989 int64_t routing_id = web_contents()->GetRoutingID();
990 int64_t rv = (process_id << 32) + routing_id;
994 int WebContents::GetProcessID() const {
995 return web_contents()->GetRenderProcessHost()->GetID();
998 WebContents::Type WebContents::GetType() const {
1002 bool WebContents::Equal(const WebContents* web_contents) const {
1003 return GetID() == web_contents->GetID();
1006 void WebContents::LoadURL(const GURL& url, const mate::Dictionary& options) {
1007 if (!url.is_valid() || url.spec().size() > url::kMaxURLChars) {
1008 Emit("did-fail-load",
1009 static_cast<int>(net::ERR_INVALID_URL),
1010 net::ErrorToShortString(net::ERR_INVALID_URL),
1011 url.possibly_invalid_spec(),
1016 content::NavigationController::LoadURLParams params(url);
1019 if (options.Get("httpReferrer", &http_referrer))
1020 params.referrer = content::Referrer(http_referrer.GetAsReferrer(),
1021 blink::WebReferrerPolicyDefault);
1023 std::string user_agent;
1024 if (options.Get("userAgent", &user_agent))
1025 web_contents()->SetUserAgentOverride(user_agent);
1027 std::string extra_headers;
1028 if (options.Get("extraHeaders", &extra_headers))
1029 params.extra_headers = extra_headers;
1031 scoped_refptr<content::ResourceRequestBodyImpl> body;
1032 if (options.Get("postData", &body)) {
1033 params.post_data = body;
1034 params.load_type = content::NavigationController::LOAD_TYPE_HTTP_POST;
1037 GURL base_url_for_data_url;
1038 if (options.Get("baseURLForDataURL", &base_url_for_data_url)) {
1039 params.base_url_for_data_url = base_url_for_data_url;
1040 params.load_type = content::NavigationController::LOAD_TYPE_DATA;
1043 params.transition_type = ui::PAGE_TRANSITION_TYPED;
1044 params.should_clear_history_list = true;
1045 params.override_user_agent = content::NavigationController::UA_OVERRIDE_TRUE;
1047 if (deferred_load_url_.id) {
1048 deferred_load_url_.params = params;
1052 web_contents()->GetController().LoadURLWithParams(params);
1053 // We have to call it right after LoadURL because the RenderViewHost is only
1054 // created after loading a page.
1055 SetBackgroundColor(web_contents());
1058 void WebContents::DownloadURL(const GURL& url) {
1059 auto browser_context = web_contents()->GetBrowserContext();
1060 auto download_manager =
1061 content::BrowserContext::GetDownloadManager(browser_context);
1063 download_manager->DownloadUrl(
1064 content::DownloadUrlParameters::CreateForWebContentsMainFrame(
1065 web_contents(), url));
1068 GURL WebContents::GetURL() const {
1069 return web_contents()->GetURL();
1072 base::string16 WebContents::GetTitle() const {
1073 return web_contents()->GetTitle();
1076 bool WebContents::IsLoading() const {
1077 return web_contents()->IsLoading();
1080 bool WebContents::IsLoadingMainFrame() const {
1081 // Comparing site instances works because Electron always creates a new site
1082 // instance when navigating, regardless of origin. See AtomBrowserClient.
1083 return (web_contents()->GetLastCommittedURL().is_empty() ||
1084 web_contents()->GetSiteInstance() !=
1085 web_contents()->GetPendingSiteInstance()) && IsLoading();
1088 bool WebContents::IsWaitingForResponse() const {
1089 return web_contents()->IsWaitingForResponse();
1092 void WebContents::Stop() {
1093 web_contents()->Stop();
1096 void WebContents::GoBack() {
1097 atom::AtomBrowserClient::SuppressRendererProcessRestartForOnce();
1098 web_contents()->GetController().GoBack();
1101 void WebContents::GoForward() {
1102 atom::AtomBrowserClient::SuppressRendererProcessRestartForOnce();
1103 web_contents()->GetController().GoForward();
1106 void WebContents::GoToOffset(int offset) {
1107 atom::AtomBrowserClient::SuppressRendererProcessRestartForOnce();
1108 web_contents()->GetController().GoToOffset(offset);
1111 const std::string WebContents::GetWebRTCIPHandlingPolicy() const {
1112 return web_contents()->
1113 GetMutableRendererPrefs()->webrtc_ip_handling_policy;
1116 void WebContents::SetWebRTCIPHandlingPolicy(
1117 const std::string& webrtc_ip_handling_policy) {
1118 if (GetWebRTCIPHandlingPolicy() == webrtc_ip_handling_policy)
1120 web_contents()->GetMutableRendererPrefs()->webrtc_ip_handling_policy =
1121 webrtc_ip_handling_policy;
1123 content::RenderViewHost* host = web_contents()->GetRenderViewHost();
1125 host->SyncRendererPrefs();
1128 bool WebContents::IsCrashed() const {
1129 return web_contents()->IsCrashed();
1132 void WebContents::SetUserAgent(const std::string& user_agent,
1133 mate::Arguments* args) {
1134 web_contents()->SetUserAgentOverride(user_agent);
1137 std::string WebContents::GetUserAgent() {
1138 return web_contents()->GetUserAgentOverride();
1141 bool WebContents::SavePage(const base::FilePath& full_file_path,
1142 const content::SavePageType& save_type,
1143 const SavePageHandler::SavePageCallback& callback) {
1144 auto handler = new SavePageHandler(web_contents(), callback);
1145 return handler->Handle(full_file_path, save_type);
1148 void WebContents::OpenDevTools(mate::Arguments* args) {
1149 if (type_ == REMOTE)
1152 if (!enable_devtools_)
1156 if (type_ == WEB_VIEW || !owner_window()) {
1158 } else if (args && args->Length() == 1) {
1159 bool detach = false;
1160 mate::Dictionary options;
1161 if (args->GetNext(&options)) {
1162 options.Get("mode", &state);
1164 // TODO(kevinsawicki) Remove in 2.0
1165 options.Get("detach", &detach);
1166 if (state.empty() && detach)
1170 managed_web_contents()->SetDockState(state);
1171 managed_web_contents()->ShowDevTools();
1174 void WebContents::CloseDevTools() {
1175 if (type_ == REMOTE)
1178 managed_web_contents()->CloseDevTools();
1181 bool WebContents::IsDevToolsOpened() {
1182 if (type_ == REMOTE)
1185 return managed_web_contents()->IsDevToolsViewShowing();
1188 bool WebContents::IsDevToolsFocused() {
1189 if (type_ == REMOTE)
1192 return managed_web_contents()->GetView()->IsDevToolsViewFocused();
1195 void WebContents::EnableDeviceEmulation(
1196 const blink::WebDeviceEmulationParams& params) {
1197 if (type_ == REMOTE)
1200 Send(new ViewMsg_EnableDeviceEmulation(routing_id(), params));
1203 void WebContents::DisableDeviceEmulation() {
1204 if (type_ == REMOTE)
1207 Send(new ViewMsg_DisableDeviceEmulation(routing_id()));
1210 void WebContents::ToggleDevTools() {
1211 if (IsDevToolsOpened())
1214 OpenDevTools(nullptr);
1217 void WebContents::InspectElement(int x, int y) {
1218 if (type_ == REMOTE)
1221 if (!enable_devtools_)
1224 if (!managed_web_contents()->GetDevToolsWebContents())
1225 OpenDevTools(nullptr);
1226 managed_web_contents()->InspectElement(x, y);
1229 void WebContents::InspectServiceWorker() {
1230 if (type_ == REMOTE)
1233 if (!enable_devtools_)
1236 for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) {
1237 if (agent_host->GetType() ==
1238 content::DevToolsAgentHost::kTypeServiceWorker) {
1239 OpenDevTools(nullptr);
1240 managed_web_contents()->AttachTo(agent_host);
1246 void WebContents::HasServiceWorker(
1247 const base::Callback<void(bool)>& callback) {
1248 auto context = GetServiceWorkerContext(web_contents());
1252 context->CheckHasServiceWorker(web_contents()->GetLastCommittedURL(),
1257 void WebContents::UnregisterServiceWorker(
1258 const base::Callback<void(bool)>& callback) {
1259 auto context = GetServiceWorkerContext(web_contents());
1263 context->UnregisterServiceWorker(web_contents()->GetLastCommittedURL(),
1267 void WebContents::SetAudioMuted(bool muted) {
1268 web_contents()->SetAudioMuted(muted);
1271 bool WebContents::IsAudioMuted() {
1272 return web_contents()->IsAudioMuted();
1275 void WebContents::Print(mate::Arguments* args) {
1276 PrintSettings settings = { false, false };
1277 if (args->Length() == 1 && !args->GetNext(&settings)) {
1282 printing::PrintViewManagerBasic::FromWebContents(web_contents())->
1283 PrintNow(web_contents()->GetMainFrame(),
1285 settings.print_background);
1288 void WebContents::PrintToPDF(const base::DictionaryValue& setting,
1289 const PrintToPDFCallback& callback) {
1290 printing::PrintPreviewMessageHandler::FromWebContents(web_contents())->
1291 PrintToPDF(setting, callback);
1294 void WebContents::AddWorkSpace(mate::Arguments* args,
1295 const base::FilePath& path) {
1297 args->ThrowError("path cannot be empty");
1300 DevToolsAddFileSystem(path);
1303 void WebContents::RemoveWorkSpace(mate::Arguments* args,
1304 const base::FilePath& path) {
1306 args->ThrowError("path cannot be empty");
1309 DevToolsRemoveFileSystem(path);
1312 void WebContents::Undo() {
1313 web_contents()->Undo();
1316 void WebContents::Redo() {
1317 web_contents()->Redo();
1320 void WebContents::Cut() {
1321 web_contents()->Cut();
1324 void WebContents::Copy() {
1325 web_contents()->Copy();
1328 void WebContents::Paste() {
1329 web_contents()->Paste();
1332 void WebContents::PasteAndMatchStyle() {
1333 web_contents()->PasteAndMatchStyle();
1336 void WebContents::Delete() {
1337 web_contents()->Delete();
1340 void WebContents::SelectAll() {
1341 web_contents()->SelectAll();
1344 void WebContents::Unselect() {
1345 web_contents()->Unselect();
1348 void WebContents::Replace(const base::string16& word) {
1349 web_contents()->Replace(word);
1352 void WebContents::ReplaceMisspelling(const base::string16& word) {
1353 web_contents()->ReplaceMisspelling(word);
1356 uint32_t WebContents::FindInPage(mate::Arguments* args) {
1357 uint32_t request_id = GetNextRequestId();
1358 base::string16 search_text;
1359 blink::WebFindOptions options;
1360 if (!args->GetNext(&search_text) || search_text.empty()) {
1361 args->ThrowError("Must provide a non-empty search content");
1365 args->GetNext(&options);
1367 web_contents()->Find(request_id, search_text, options);
1371 void WebContents::StopFindInPage(content::StopFindAction action) {
1372 web_contents()->StopFinding(action);
1375 void WebContents::ShowDefinitionForSelection() {
1376 #if defined(OS_MACOSX)
1377 const auto view = web_contents()->GetRenderWidgetHostView();
1379 view->ShowDefinitionForSelection();
1383 void WebContents::CopyImageAt(int x, int y) {
1384 const auto host = web_contents()->GetMainFrame();
1386 host->CopyImageAt(x, y);
1389 void WebContents::Focus() {
1390 web_contents()->Focus();
1393 #if !defined(OS_MACOSX)
1394 bool WebContents::IsFocused() const {
1395 auto view = web_contents()->GetRenderWidgetHostView();
1396 if (!view) return false;
1398 #if defined(USE_EFL)
1401 if (GetType() != BACKGROUND_PAGE) {
1402 auto window = web_contents()->GetNativeView()->GetToplevelWindow();
1403 if (window && !window->IsVisible())
1408 return view->HasFocus();
1412 void WebContents::TabTraverse(bool reverse) {
1413 web_contents()->FocusThroughTabTraversal(reverse);
1416 bool WebContents::SendIPCMessage(bool all_frames,
1417 const base::string16& channel,
1418 const base::ListValue& args) {
1419 return Send(new AtomViewMsg_Message(routing_id(), all_frames, channel, args));
1422 void WebContents::SendInputEvent(v8::Isolate* isolate,
1423 v8::Local<v8::Value> input_event) {
1424 const auto view = web_contents()->GetRenderWidgetHostView();
1427 const auto host = view->GetRenderWidgetHost();
1431 int type = mate::GetWebInputEventType(isolate, input_event);
1432 if (blink::WebInputEvent::isMouseEventType(type)) {
1433 blink::WebMouseEvent mouse_event;
1434 if (mate::ConvertFromV8(isolate, input_event, &mouse_event)) {
1435 host->ForwardMouseEvent(mouse_event);
1438 } else if (blink::WebInputEvent::isKeyboardEventType(type)) {
1439 content::NativeWebKeyboardEvent keyboard_event;
1440 if (mate::ConvertFromV8(isolate, input_event, &keyboard_event)) {
1441 host->ForwardKeyboardEvent(keyboard_event);
1444 } else if (type == blink::WebInputEvent::MouseWheel) {
1445 blink::WebMouseWheelEvent mouse_wheel_event;
1446 if (mate::ConvertFromV8(isolate, input_event, &mouse_wheel_event)) {
1447 host->ForwardWheelEvent(mouse_wheel_event);
1452 isolate->ThrowException(v8::Exception::Error(mate::StringToV8(
1453 isolate, "Invalid event object")));
1456 void WebContents::BeginFrameSubscription(mate::Arguments* args) {
1457 bool only_dirty = false;
1458 FrameSubscriber::FrameCaptureCallback callback;
1460 args->GetNext(&only_dirty);
1461 if (!args->GetNext(&callback)) {
1466 const auto view = web_contents()->GetRenderWidgetHostView();
1468 std::unique_ptr<FrameSubscriber> frame_subscriber(new FrameSubscriber(
1469 isolate(), view, callback, only_dirty));
1470 view->BeginFrameSubscription(std::move(frame_subscriber));
1474 void WebContents::EndFrameSubscription() {
1475 const auto view = web_contents()->GetRenderWidgetHostView();
1477 view->EndFrameSubscription();
1480 void WebContents::StartDrag(const mate::Dictionary& item,
1481 mate::Arguments* args) {
1482 base::FilePath file;
1483 std::vector<base::FilePath> files;
1484 if (!item.Get("files", &files) && item.Get("file", &file)) {
1485 files.push_back(file);
1488 mate::Handle<NativeImage> icon;
1489 if (!item.Get("icon", &icon) && !file.empty()) {
1490 // TODO(zcbenz): Set default icon from file.
1494 if (icon.IsEmpty()) {
1495 args->ThrowError("Must specify 'icon' option");
1499 #if defined(OS_MACOSX)
1500 // NSWindow.dragImage requires a non-empty NSImage
1501 if (icon->image().IsEmpty()) {
1502 args->ThrowError("Must specify non-empty 'icon' option");
1508 if (!files.empty()) {
1509 base::MessageLoop::ScopedNestableTaskAllower allow(
1510 base::MessageLoop::current());
1511 DragFileItems(files, icon->image(), web_contents()->GetNativeView());
1513 args->ThrowError("Must specify either 'file' or 'files' option");
1517 void WebContents::CapturePage(mate::Arguments* args) {
1519 base::Callback<void(const gfx::Image&)> callback;
1521 if (!(args->Length() == 1 && args->GetNext(&callback)) &&
1522 !(args->Length() == 2 && args->GetNext(&rect)
1523 && args->GetNext(&callback))) {
1528 const auto view = web_contents()->GetRenderWidgetHostView();
1529 const auto host = view ? view->GetRenderWidgetHost() : nullptr;
1530 if (!view || !host) {
1531 callback.Run(gfx::Image());
1535 // Capture full page if user doesn't specify a |rect|.
1536 const gfx::Size view_size = rect.IsEmpty() ? view->GetViewBounds().size() :
1539 // By default, the requested bitmap size is the view size in screen
1540 // coordinates. However, if there's more pixel detail available on the
1541 // current system, increase the requested bitmap size to capture it all.
1542 gfx::Size bitmap_size = view_size;
1543 const gfx::NativeView native_view = view->GetNativeView();
1545 display::Screen::GetScreen()->GetDisplayNearestWindow(native_view)
1546 .device_scale_factor();
1548 bitmap_size = gfx::ScaleToCeiledSize(view_size, scale);
1550 host->CopyFromBackingStore(gfx::Rect(rect.origin(), view_size),
1552 base::Bind(&OnCapturePageDone, callback),
1553 kBGRA_8888_SkColorType);
1556 void WebContents::OnCursorChange(const content::WebCursor& cursor) {
1557 content::WebCursor::CursorInfo info;
1558 cursor.GetCursorInfo(&info);
1560 if (cursor.IsCustom()) {
1561 Emit("cursor-changed", CursorTypeToString(info),
1562 gfx::Image::CreateFrom1xBitmap(info.custom_image),
1563 info.image_scale_factor,
1564 gfx::Size(info.custom_image.width(), info.custom_image.height()),
1567 Emit("cursor-changed", CursorTypeToString(info));
1571 void WebContents::SetSize(const SetSizeParams& params) {
1572 if (guest_delegate_)
1573 guest_delegate_->SetSize(params);
1576 bool WebContents::IsGuest() const {
1577 return type_ == WEB_VIEW;
1580 bool WebContents::IsOffScreen() const {
1581 return type_ == OFF_SCREEN;
1584 void WebContents::OnPaint(const gfx::Rect& dirty_rect, const SkBitmap& bitmap) {
1585 mate::Handle<NativeImage> image =
1586 NativeImage::Create(isolate(), gfx::Image::CreateFrom1xBitmap(bitmap));
1587 Emit("paint", dirty_rect, image);
1590 void WebContents::StartPainting() {
1594 auto* osr_rwhv = static_cast<OffScreenRenderWidgetHostView*>(
1595 web_contents()->GetRenderWidgetHostView());
1597 osr_rwhv->SetPainting(true);
1600 void WebContents::StopPainting() {
1604 auto* osr_rwhv = static_cast<OffScreenRenderWidgetHostView*>(
1605 web_contents()->GetRenderWidgetHostView());
1607 osr_rwhv->SetPainting(false);
1610 bool WebContents::IsPainting() const {
1614 const auto* osr_rwhv = static_cast<OffScreenRenderWidgetHostView*>(
1615 web_contents()->GetRenderWidgetHostView());
1616 return osr_rwhv && osr_rwhv->IsPainting();
1619 void WebContents::SetFrameRate(int frame_rate) {
1623 auto* osr_rwhv = static_cast<OffScreenRenderWidgetHostView*>(
1624 web_contents()->GetRenderWidgetHostView());
1626 osr_rwhv->SetFrameRate(frame_rate);
1629 int WebContents::GetFrameRate() const {
1633 const auto* osr_rwhv = static_cast<OffScreenRenderWidgetHostView*>(
1634 web_contents()->GetRenderWidgetHostView());
1635 return osr_rwhv ? osr_rwhv->GetFrameRate() : 0;
1638 void WebContents::Invalidate() {
1639 if (IsOffScreen()) {
1640 auto* osr_rwhv = static_cast<OffScreenRenderWidgetHostView*>(
1641 web_contents()->GetRenderWidgetHostView());
1643 osr_rwhv->Invalidate();
1645 const auto window = owner_window();
1647 window->Invalidate();
1651 void WebContents::SetZoomLevel(double level) {
1652 zoom_controller_->SetZoomLevel(level);
1655 double WebContents::GetZoomLevel() {
1656 return zoom_controller_->GetZoomLevel();
1659 void WebContents::SetZoomFactor(double factor) {
1660 auto level = content::ZoomFactorToZoomLevel(factor);
1661 SetZoomLevel(level);
1664 double WebContents::GetZoomFactor() {
1665 auto level = GetZoomLevel();
1666 return content::ZoomLevelToZoomFactor(level);
1669 void WebContents::OnSetTemporaryZoomLevel(double level,
1670 IPC::Message* reply_msg) {
1671 zoom_controller_->SetTemporaryZoomLevel(level);
1672 double new_level = zoom_controller_->GetZoomLevel();
1673 AtomViewHostMsg_SetTemporaryZoomLevel::WriteReplyParams(reply_msg, new_level);
1677 void WebContents::OnGetZoomLevel(IPC::Message* reply_msg) {
1678 AtomViewHostMsg_GetZoomLevel::WriteReplyParams(reply_msg, GetZoomLevel());
1682 v8::Local<v8::Value> WebContents::GetWebPreferences(v8::Isolate* isolate) {
1683 WebContentsPreferences* web_preferences =
1684 WebContentsPreferences::FromWebContents(web_contents());
1685 return mate::ConvertToV8(isolate, *web_preferences->web_preferences());
1688 v8::Local<v8::Value> WebContents::GetOwnerBrowserWindow() {
1690 return Window::From(isolate(), owner_window());
1692 return v8::Null(isolate());
1695 int32_t WebContents::ID() const {
1696 return weak_map_id();
1699 v8::Local<v8::Value> WebContents::Session(v8::Isolate* isolate) {
1700 return v8::Local<v8::Value>::New(isolate, session_);
1703 content::WebContents* WebContents::HostWebContents() {
1706 return embedder_->web_contents();
1709 void WebContents::SetEmbedder(const WebContents* embedder) {
1711 NativeWindow* owner_window = nullptr;
1712 auto relay = NativeWindowRelay::FromWebContents(embedder->web_contents());
1714 owner_window = relay->window.get();
1717 SetOwnerWindow(owner_window);
1719 content::RenderWidgetHostView* rwhv =
1720 web_contents()->GetRenderWidgetHostView();
1728 v8::Local<v8::Value> WebContents::DevToolsWebContents(v8::Isolate* isolate) {
1729 if (devtools_web_contents_.IsEmpty())
1730 return v8::Null(isolate);
1732 return v8::Local<v8::Value>::New(isolate, devtools_web_contents_);
1735 v8::Local<v8::Value> WebContents::Debugger(v8::Isolate* isolate) {
1736 if (debugger_.IsEmpty()) {
1737 auto handle = atom::api::Debugger::Create(isolate, web_contents());
1738 debugger_.Reset(isolate, handle.ToV8());
1740 return v8::Local<v8::Value>::New(isolate, debugger_);
1744 void WebContents::BuildPrototype(v8::Isolate* isolate,
1745 v8::Local<v8::FunctionTemplate> prototype) {
1746 prototype->SetClassName(mate::StringToV8(isolate, "WebContents"));
1747 mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
1749 .SetMethod("getId", &WebContents::GetID)
1750 .SetMethod("getProcessId", &WebContents::GetProcessID)
1751 .SetMethod("equal", &WebContents::Equal)
1752 .SetMethod("_loadURL", &WebContents::LoadURL)
1753 .SetMethod("downloadURL", &WebContents::DownloadURL)
1754 .SetMethod("_getURL", &WebContents::GetURL)
1755 .SetMethod("getTitle", &WebContents::GetTitle)
1756 .SetMethod("isLoading", &WebContents::IsLoading)
1757 .SetMethod("isLoadingMainFrame", &WebContents::IsLoadingMainFrame)
1758 .SetMethod("isWaitingForResponse", &WebContents::IsWaitingForResponse)
1759 .SetMethod("_stop", &WebContents::Stop)
1760 .SetMethod("_goBack", &WebContents::GoBack)
1761 .SetMethod("_goForward", &WebContents::GoForward)
1762 .SetMethod("_goToOffset", &WebContents::GoToOffset)
1763 .SetMethod("isCrashed", &WebContents::IsCrashed)
1764 .SetMethod("setUserAgent", &WebContents::SetUserAgent)
1765 .SetMethod("getUserAgent", &WebContents::GetUserAgent)
1766 .SetMethod("savePage", &WebContents::SavePage)
1767 .SetMethod("openDevTools", &WebContents::OpenDevTools)
1768 .SetMethod("closeDevTools", &WebContents::CloseDevTools)
1769 .SetMethod("isDevToolsOpened", &WebContents::IsDevToolsOpened)
1770 .SetMethod("isDevToolsFocused", &WebContents::IsDevToolsFocused)
1771 .SetMethod("enableDeviceEmulation",
1772 &WebContents::EnableDeviceEmulation)
1773 .SetMethod("disableDeviceEmulation",
1774 &WebContents::DisableDeviceEmulation)
1775 .SetMethod("toggleDevTools", &WebContents::ToggleDevTools)
1776 .SetMethod("inspectElement", &WebContents::InspectElement)
1777 .SetMethod("setAudioMuted", &WebContents::SetAudioMuted)
1778 .SetMethod("isAudioMuted", &WebContents::IsAudioMuted)
1779 .SetMethod("undo", &WebContents::Undo)
1780 .SetMethod("redo", &WebContents::Redo)
1781 .SetMethod("cut", &WebContents::Cut)
1782 .SetMethod("copy", &WebContents::Copy)
1783 .SetMethod("paste", &WebContents::Paste)
1784 .SetMethod("pasteAndMatchStyle", &WebContents::PasteAndMatchStyle)
1785 .SetMethod("delete", &WebContents::Delete)
1786 .SetMethod("selectAll", &WebContents::SelectAll)
1787 .SetMethod("unselect", &WebContents::Unselect)
1788 .SetMethod("replace", &WebContents::Replace)
1789 .SetMethod("replaceMisspelling", &WebContents::ReplaceMisspelling)
1790 .SetMethod("findInPage", &WebContents::FindInPage)
1791 .SetMethod("stopFindInPage", &WebContents::StopFindInPage)
1792 .SetMethod("focus", &WebContents::Focus)
1793 .SetMethod("isFocused", &WebContents::IsFocused)
1794 .SetMethod("tabTraverse", &WebContents::TabTraverse)
1795 .SetMethod("_send", &WebContents::SendIPCMessage)
1796 .SetMethod("sendInputEvent", &WebContents::SendInputEvent)
1797 .SetMethod("beginFrameSubscription",
1798 &WebContents::BeginFrameSubscription)
1799 .SetMethod("endFrameSubscription", &WebContents::EndFrameSubscription)
1800 .SetMethod("startDrag", &WebContents::StartDrag)
1801 .SetMethod("setSize", &WebContents::SetSize)
1802 .SetMethod("isGuest", &WebContents::IsGuest)
1803 .SetMethod("isOffscreen", &WebContents::IsOffScreen)
1804 .SetMethod("startPainting", &WebContents::StartPainting)
1805 .SetMethod("stopPainting", &WebContents::StopPainting)
1806 .SetMethod("isPainting", &WebContents::IsPainting)
1807 .SetMethod("setFrameRate", &WebContents::SetFrameRate)
1808 .SetMethod("getFrameRate", &WebContents::GetFrameRate)
1809 .SetMethod("invalidate", &WebContents::Invalidate)
1810 .SetMethod("setZoomLevel", &WebContents::SetZoomLevel)
1811 .SetMethod("_getZoomLevel", &WebContents::GetZoomLevel)
1812 .SetMethod("setZoomFactor", &WebContents::SetZoomFactor)
1813 .SetMethod("_getZoomFactor", &WebContents::GetZoomFactor)
1814 .SetMethod("getType", &WebContents::GetType)
1815 .SetMethod("getWebPreferences", &WebContents::GetWebPreferences)
1816 .SetMethod("getOwnerBrowserWindow", &WebContents::GetOwnerBrowserWindow)
1817 .SetMethod("hasServiceWorker", &WebContents::HasServiceWorker)
1818 .SetMethod("unregisterServiceWorker",
1819 &WebContents::UnregisterServiceWorker)
1820 .SetMethod("inspectServiceWorker", &WebContents::InspectServiceWorker)
1821 .SetMethod("print", &WebContents::Print)
1822 .SetMethod("_printToPDF", &WebContents::PrintToPDF)
1823 .SetMethod("addWorkSpace", &WebContents::AddWorkSpace)
1824 .SetMethod("removeWorkSpace", &WebContents::RemoveWorkSpace)
1825 .SetMethod("showDefinitionForSelection",
1826 &WebContents::ShowDefinitionForSelection)
1827 .SetMethod("copyImageAt", &WebContents::CopyImageAt)
1828 .SetMethod("capturePage", &WebContents::CapturePage)
1829 .SetMethod("setEmbedder", &WebContents::SetEmbedder)
1830 .SetMethod("setWebRTCIPHandlingPolicy",
1831 &WebContents::SetWebRTCIPHandlingPolicy)
1832 .SetMethod("getWebRTCIPHandlingPolicy",
1833 &WebContents::GetWebRTCIPHandlingPolicy)
1834 .SetProperty("id", &WebContents::ID)
1835 .SetProperty("session", &WebContents::Session)
1836 .SetProperty("hostWebContents", &WebContents::HostWebContents)
1837 .SetProperty("devToolsWebContents", &WebContents::DevToolsWebContents)
1838 .SetProperty("debugger", &WebContents::Debugger);
1841 AtomBrowserContext* WebContents::GetBrowserContext() const {
1842 return static_cast<AtomBrowserContext*>(web_contents()->GetBrowserContext());
1845 void WebContents::OnRendererMessage(const base::string16& channel,
1846 const base::ListValue& args) {
1847 // webContents.emit(channel, new Event(), args...);
1848 Emit(base::UTF16ToUTF8(channel), args);
1851 void WebContents::OnRendererMessageSync(const base::string16& channel,
1852 const base::ListValue& args,
1853 IPC::Message* message) {
1854 // webContents.emit(channel, new Event(sender, message), args...);
1855 EmitWithSender(base::UTF16ToUTF8(channel), web_contents(), message, args);
1859 mate::Handle<WebContents> WebContents::CreateFrom(
1860 v8::Isolate* isolate, content::WebContents* web_contents) {
1861 // We have an existing WebContents object in JS.
1862 auto existing = TrackableObject::FromWrappedClass(isolate, web_contents);
1864 return mate::CreateHandle(isolate, static_cast<WebContents*>(existing));
1866 // Otherwise create a new WebContents wrapper object.
1867 return mate::CreateHandle(isolate, new WebContents(isolate, web_contents,
1871 mate::Handle<WebContents> WebContents::CreateFrom(
1872 v8::Isolate* isolate, content::WebContents* web_contents, Type type) {
1873 // Otherwise create a new WebContents wrapper object.
1874 return mate::CreateHandle(isolate, new WebContents(isolate, web_contents,
1879 mate::Handle<WebContents> WebContents::Create(
1880 v8::Isolate* isolate, const mate::Dictionary& options) {
1881 return mate::CreateHandle(isolate, new WebContents(isolate, options));
1890 using atom::api::WebContents;
1892 void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused,
1893 v8::Local<v8::Context> context, void* priv) {
1894 v8::Isolate* isolate = context->GetIsolate();
1895 mate::Dictionary dict(isolate, exports);
1896 dict.Set("WebContents", WebContents::GetConstructor(isolate)->GetFunction());
1897 dict.SetMethod("create", &WebContents::Create);
1898 dict.SetMethod("fromId", &mate::TrackableObject<WebContents>::FromWeakMapID);
1899 dict.SetMethod("getAllWebContents",
1900 &mate::TrackableObject<WebContents>::GetAll);
1905 NODE_MODULE_CONTEXT_AWARE_BUILTIN(atom_browser_web_contents, Initialize)