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"
10 #include "atom/browser/api/atom_api_debugger.h"
11 #include "atom/browser/api/atom_api_session.h"
12 #include "atom/browser/api/atom_api_window.h"
13 #include "atom/browser/atom_browser_client.h"
14 #include "atom/browser/atom_browser_context.h"
15 #include "atom/browser/atom_browser_main_parts.h"
16 #include "atom/browser/lib/bluetooth_chooser.h"
17 #include "atom/browser/native_window.h"
18 #include "atom/browser/net/atom_network_delegate.h"
19 #include "atom/browser/osr/osr_output_device.h"
20 #include "atom/browser/osr/osr_render_widget_host_view.h"
21 #include "atom/browser/osr/osr_web_contents_view.h"
22 #include "atom/browser/ui/drag_util.h"
23 #include "atom/browser/web_contents_permission_helper.h"
24 #include "atom/browser/web_contents_preferences.h"
25 #include "atom/browser/web_contents_zoom_controller.h"
26 #include "atom/browser/web_view_guest_delegate.h"
27 #include "atom/common/api/api_messages.h"
28 #include "atom/common/api/event_emitter_caller.h"
29 #include "atom/common/color_util.h"
30 #include "atom/common/mouse_util.h"
31 #include "atom/common/native_mate_converters/blink_converter.h"
32 #include "atom/common/native_mate_converters/callback.h"
33 #include "atom/common/native_mate_converters/content_converter.h"
34 #include "atom/common/native_mate_converters/file_path_converter.h"
35 #include "atom/common/native_mate_converters/gfx_converter.h"
36 #include "atom/common/native_mate_converters/gurl_converter.h"
37 #include "atom/common/native_mate_converters/image_converter.h"
38 #include "atom/common/native_mate_converters/net_converter.h"
39 #include "atom/common/native_mate_converters/string16_converter.h"
40 #include "atom/common/native_mate_converters/value_converter.h"
41 #include "atom/common/options_switches.h"
42 #include "base/strings/utf_string_conversions.h"
43 #include "base/threading/thread_task_runner_handle.h"
44 #include "brightray/browser/inspectable_web_contents.h"
45 #include "brightray/browser/inspectable_web_contents_view.h"
46 #include "chrome/browser/printing/print_preview_message_handler.h"
47 #include "chrome/browser/printing/print_view_manager_basic.h"
48 #include "chrome/browser/ssl/security_state_tab_helper.h"
49 #include "content/browser/frame_host/navigation_entry_impl.h"
50 #include "content/browser/renderer_host/render_widget_host_impl.h"
51 #include "content/browser/web_contents/web_contents_impl.h"
52 #include "content/common/view_messages.h"
53 #include "content/public/browser/favicon_status.h"
54 #include "content/public/browser/native_web_keyboard_event.h"
55 #include "content/public/browser/navigation_details.h"
56 #include "content/public/browser/navigation_entry.h"
57 #include "content/public/browser/navigation_handle.h"
58 #include "content/public/browser/notification_details.h"
59 #include "content/public/browser/notification_source.h"
60 #include "content/public/browser/notification_types.h"
61 #include "content/public/browser/plugin_service.h"
62 #include "content/public/browser/render_frame_host.h"
63 #include "content/public/browser/render_process_host.h"
64 #include "content/public/browser/render_view_host.h"
65 #include "content/public/browser/render_widget_host.h"
66 #include "content/public/browser/render_widget_host_view.h"
67 #include "content/public/browser/resource_request_details.h"
68 #include "content/public/browser/service_worker_context.h"
69 #include "content/public/browser/site_instance.h"
70 #include "content/public/browser/storage_partition.h"
71 #include "content/public/browser/web_contents.h"
72 #include "content/public/common/context_menu_params.h"
73 #include "native_mate/dictionary.h"
74 #include "native_mate/object_template_builder.h"
75 #include "net/url_request/url_request_context.h"
76 #include "third_party/WebKit/public/platform/WebInputEvent.h"
77 #include "third_party/WebKit/public/web/WebFindOptions.h"
78 #include "ui/display/screen.h"
80 #if !defined(OS_MACOSX) && !defined(USE_EFL)
81 #include "ui/aura/window.h"
84 #include "atom/common/node_includes.h"
88 struct PrintSettings {
90 bool print_background;
98 struct Converter<atom::SetSizeParams> {
99 static bool FromV8(v8::Isolate* isolate,
100 v8::Local<v8::Value> val,
101 atom::SetSizeParams* out) {
102 mate::Dictionary params;
103 if (!ConvertFromV8(isolate, val, ¶ms))
106 if (params.Get("enableAutoSize", &autosize))
107 out->enable_auto_size.reset(new bool(true));
109 if (params.Get("min", &size))
110 out->min_size.reset(new gfx::Size(size));
111 if (params.Get("max", &size))
112 out->max_size.reset(new gfx::Size(size));
113 if (params.Get("normal", &size))
114 out->normal_size.reset(new gfx::Size(size));
120 struct Converter<PrintSettings> {
121 static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val,
122 PrintSettings* out) {
123 mate::Dictionary dict;
124 if (!ConvertFromV8(isolate, val, &dict))
126 dict.Get("silent", &(out->silent));
127 dict.Get("printBackground", &(out->print_background));
133 struct Converter<WindowOpenDisposition> {
134 static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
135 WindowOpenDisposition val) {
136 std::string disposition = "other";
138 case WindowOpenDisposition::CURRENT_TAB:
139 disposition = "default";
141 case WindowOpenDisposition::NEW_FOREGROUND_TAB:
142 disposition = "foreground-tab";
144 case WindowOpenDisposition::NEW_BACKGROUND_TAB:
145 disposition = "background-tab";
147 case WindowOpenDisposition::NEW_POPUP:
148 case WindowOpenDisposition::NEW_WINDOW:
149 disposition = "new-window";
151 case WindowOpenDisposition::SAVE_TO_DISK:
152 disposition = "save-to-disk";
157 return mate::ConvertToV8(isolate, disposition);
162 struct Converter<content::SavePageType> {
163 static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val,
164 content::SavePageType* out) {
165 std::string save_type;
166 if (!ConvertFromV8(isolate, val, &save_type))
168 save_type = base::ToLowerASCII(save_type);
169 if (save_type == "htmlonly") {
170 *out = content::SAVE_PAGE_TYPE_AS_ONLY_HTML;
171 } else if (save_type == "htmlcomplete") {
172 *out = content::SAVE_PAGE_TYPE_AS_COMPLETE_HTML;
173 } else if (save_type == "mhtml") {
174 *out = content::SAVE_PAGE_TYPE_AS_MHTML;
183 struct Converter<atom::api::WebContents::Type> {
184 static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
185 atom::api::WebContents::Type val) {
186 using Type = atom::api::WebContents::Type;
187 std::string type = "";
189 case Type::BACKGROUND_PAGE: type = "backgroundPage"; break;
190 case Type::BROWSER_WINDOW: type = "window"; break;
191 case Type::BROWSER_VIEW: type = "browserView"; break;
192 case Type::REMOTE: type = "remote"; break;
193 case Type::WEB_VIEW: type = "webview"; break;
194 case Type::OFF_SCREEN: type = "offscreen"; break;
197 return mate::ConvertToV8(isolate, type);
200 static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val,
201 atom::api::WebContents::Type* out) {
202 using Type = atom::api::WebContents::Type;
204 if (!ConvertFromV8(isolate, val, &type))
206 if (type == "backgroundPage") {
207 *out = Type::BACKGROUND_PAGE;
208 } else if (type == "browserView") {
209 *out = Type::BROWSER_VIEW;
210 } else if (type == "webview") {
211 *out = Type::WEB_VIEW;
212 } else if (type == "offscreen") {
213 *out = Type::OFF_SCREEN;
230 content::ServiceWorkerContext* GetServiceWorkerContext(
231 const content::WebContents* web_contents) {
232 auto context = web_contents->GetBrowserContext();
233 auto site_instance = web_contents->GetSiteInstance();
234 if (!context || !site_instance)
237 auto storage_partition =
238 content::BrowserContext::GetStoragePartition(context, site_instance);
239 if (!storage_partition)
242 return storage_partition->GetServiceWorkerContext();
245 // Called when CapturePage is done.
246 void OnCapturePageDone(const base::Callback<void(const gfx::Image&)>& callback,
247 const SkBitmap& bitmap,
248 content::ReadbackResponse response) {
249 callback.Run(gfx::Image::CreateFrom1xBitmap(bitmap));
252 // Set the background color of RenderWidgetHostView.
253 void SetBackgroundColor(content::WebContents* web_contents) {
254 const auto view = web_contents->GetRenderWidgetHostView();
256 WebContentsPreferences* web_preferences =
257 WebContentsPreferences::FromWebContents(web_contents);
258 std::string color_name;
259 if (web_preferences->web_preferences()->GetString(options::kBackgroundColor,
261 view->SetBackgroundColor(ParseHexColor(color_name));
263 view->SetBackgroundColor(SK_ColorTRANSPARENT);
270 WebContents::WebContents(v8::Isolate* isolate,
271 content::WebContents* web_contents,
273 : content::WebContentsObserver(web_contents),
275 zoom_controller_(nullptr),
278 background_throttling_(true),
279 enable_devtools_(true) {
280 if (type == REMOTE) {
281 web_contents->SetUserAgentOverride(GetBrowserContext()->GetUserAgent());
283 AttachAsUserData(web_contents);
285 const mate::Dictionary options = mate::Dictionary::CreateEmpty(isolate);
286 auto session = Session::CreateFrom(isolate, GetBrowserContext());
287 session_.Reset(isolate, session.ToV8());
288 InitWithSessionAndOptions(isolate, web_contents, session, options);
292 WebContents::WebContents(v8::Isolate* isolate, const mate::Dictionary& options)
293 : embedder_(nullptr),
294 zoom_controller_(nullptr),
295 type_(BROWSER_WINDOW),
297 background_throttling_(true),
298 enable_devtools_(true) {
300 options.Get("backgroundThrottling", &background_throttling_);
302 // FIXME(zcbenz): We should read "type" parameter for better design, but
303 // on Windows we have encountered a compiler bug that if we read "type"
304 // from |options| and then set |type_|, a memory corruption will happen
305 // and Electron will soon crash.
306 // Remvoe this after we upgraded to use VS 2015 Update 3.
308 if (options.Get("isGuest", &b) && b)
310 else if (options.Get("isBackgroundPage", &b) && b)
311 type_ = BACKGROUND_PAGE;
312 else if (options.Get("isBrowserView", &b) && b)
313 type_ = BROWSER_VIEW;
314 else if (options.Get("offscreen", &b) && b)
317 // Whether to enable DevTools.
318 options.Get("devTools", &enable_devtools_);
320 // Obtain the session.
321 std::string partition;
322 mate::Handle<api::Session> session;
323 if (options.Get("session", &session)) {
324 } else if (options.Get("partition", &partition)) {
325 session = Session::FromPartition(isolate, partition);
327 // Use the default session if not specified.
328 session = Session::FromPartition(isolate, "");
330 session_.Reset(isolate, session.ToV8());
332 content::WebContents* web_contents;
334 scoped_refptr<content::SiteInstance> site_instance =
335 content::SiteInstance::CreateForURL(
336 session->browser_context(), GURL("chrome-guest://fake-host"));
337 content::WebContents::CreateParams params(
338 session->browser_context(), site_instance);
339 guest_delegate_.reset(new WebViewGuestDelegate);
340 params.guest_delegate = guest_delegate_.get();
341 web_contents = content::WebContents::Create(params);
342 } else if (IsOffScreen()) {
343 bool transparent = false;
344 options.Get("transparent", &transparent);
346 content::WebContents::CreateParams params(session->browser_context());
347 auto* view = new OffScreenWebContentsView(
348 transparent, base::Bind(&WebContents::OnPaint, base::Unretained(this)));
350 params.delegate_view = view;
352 web_contents = content::WebContents::Create(params);
353 view->SetWebContents(web_contents);
355 content::WebContents::CreateParams params(session->browser_context());
356 web_contents = content::WebContents::Create(params);
359 InitWithSessionAndOptions(isolate, web_contents, session, options);
362 void WebContents::InitWithSessionAndOptions(v8::Isolate* isolate,
363 content::WebContents *web_contents,
364 mate::Handle<api::Session> session,
365 const mate::Dictionary& options) {
366 content::WebContentsObserver::Observe(web_contents);
367 InitWithWebContents(web_contents, session->browser_context());
369 managed_web_contents()->GetView()->SetDelegate(this);
371 // Save the preferences in C++.
372 new WebContentsPreferences(web_contents, options);
374 // Initialize permission helper.
375 WebContentsPermissionHelper::CreateForWebContents(web_contents);
376 // Initialize security state client.
377 SecurityStateTabHelper::CreateForWebContents(web_contents);
378 // Initialize zoom controller.
379 WebContentsZoomController::CreateForWebContents(web_contents);
380 zoom_controller_ = WebContentsZoomController::FromWebContents(web_contents);
382 if (options.Get(options::kZoomFactor, &zoom_factor))
383 zoom_controller_->SetDefaultZoomFactor(zoom_factor);
385 web_contents->SetUserAgentOverride(GetBrowserContext()->GetUserAgent());
388 guest_delegate_->Initialize(this);
390 NativeWindow* owner_window = nullptr;
391 if (options.Get("embedder", &embedder_) && embedder_) {
392 // New WebContents's owner_window is the embedder's owner_window.
394 NativeWindowRelay::FromWebContents(embedder_->web_contents());
396 owner_window = relay->window.get();
399 SetOwnerWindow(owner_window);
402 const content::NavigationController* controller =
403 &web_contents->GetController();
404 registrar_.Add(this, content::NOTIFICATION_NAV_ENTRY_PENDING,
405 content::Source<content::NavigationController>(controller));
408 AttachAsUserData(web_contents);
411 WebContents::~WebContents() {
412 // The destroy() is called.
413 if (managed_web_contents()) {
414 // For webview we need to tell content module to do some cleanup work before
416 if (type_ == WEB_VIEW)
417 guest_delegate_->Destroy();
419 RenderViewDeleted(web_contents()->GetRenderViewHost());
420 DestroyWebContents();
424 void WebContents::DestroyWebContents() {
425 // This event is only for internal use, which is emitted when WebContents is
427 Emit("will-destroy");
428 ResetManagedWebContents();
431 bool WebContents::DidAddMessageToConsole(content::WebContents* source,
433 const base::string16& message,
435 const base::string16& source_id) {
436 if (type_ == BROWSER_WINDOW || type_ == OFF_SCREEN) {
439 Emit("console-message", level, message, line_no, source_id);
444 void WebContents::OnCreateWindow(
445 const GURL& target_url,
446 const std::string& frame_name,
447 WindowOpenDisposition disposition,
448 const std::vector<std::string>& features,
449 const scoped_refptr<content::ResourceRequestBodyImpl>& body) {
450 if (type_ == BROWSER_WINDOW || type_ == OFF_SCREEN)
451 Emit("-new-window", target_url, frame_name, disposition, features, body);
453 Emit("new-window", target_url, frame_name, disposition, features);
456 void WebContents::WebContentsCreated(content::WebContents* source_contents,
457 int opener_render_process_id,
458 int opener_render_frame_id,
459 const std::string& frame_name,
460 const GURL& target_url,
461 content::WebContents* new_contents) {
462 v8::Locker locker(isolate());
463 v8::HandleScope handle_scope(isolate());
464 auto api_web_contents = CreateFrom(isolate(), new_contents, BROWSER_WINDOW);
465 Emit("-web-contents-created", api_web_contents, target_url, frame_name);
468 void WebContents::AddNewContents(content::WebContents* source,
469 content::WebContents* new_contents,
470 WindowOpenDisposition disposition,
471 const gfx::Rect& initial_rect,
474 v8::Locker locker(isolate());
475 v8::HandleScope handle_scope(isolate());
476 auto api_web_contents = CreateFrom(isolate(), new_contents);
477 if (Emit("-add-new-contents", api_web_contents, disposition, user_gesture,
478 initial_rect.x(), initial_rect.y(), initial_rect.width(),
479 initial_rect.height())) {
480 api_web_contents->DestroyWebContents();
484 content::WebContents* WebContents::OpenURLFromTab(
485 content::WebContents* source,
486 const content::OpenURLParams& params) {
487 if (params.disposition != WindowOpenDisposition::CURRENT_TAB) {
488 if (type_ == BROWSER_WINDOW || type_ == OFF_SCREEN)
489 Emit("-new-window", params.url, "", params.disposition);
491 Emit("new-window", params.url, "", params.disposition);
495 // Give user a chance to cancel navigation.
496 if (Emit("will-navigate", params.url))
499 // Don't load the URL if the web contents was marked as destroyed from a
500 // will-navigate event listener
504 return CommonWebContentsDelegate::OpenURLFromTab(source, params);
507 void WebContents::BeforeUnloadFired(content::WebContents* tab,
509 bool* proceed_to_fire_unload) {
510 if (type_ == BROWSER_WINDOW || type_ == OFF_SCREEN)
511 *proceed_to_fire_unload = proceed;
513 *proceed_to_fire_unload = true;
516 void WebContents::MoveContents(content::WebContents* source,
517 const gfx::Rect& pos) {
521 void WebContents::CloseContents(content::WebContents* source) {
524 if ((type_ == BROWSER_WINDOW || type_ == OFF_SCREEN) && owner_window())
525 owner_window()->CloseContents(source);
528 void WebContents::ActivateContents(content::WebContents* source) {
532 void WebContents::UpdateTargetURL(content::WebContents* source,
534 Emit("update-target-url", url);
537 bool WebContents::IsPopupOrPanel(const content::WebContents* source) const {
538 return type_ == BROWSER_WINDOW;
541 void WebContents::HandleKeyboardEvent(
542 content::WebContents* source,
543 const content::NativeWebKeyboardEvent& event) {
544 if (type_ == WEB_VIEW && embedder_) {
545 // Send the unhandled keyboard events back to the embedder.
546 embedder_->HandleKeyboardEvent(source, event);
548 // Go to the default keyboard handling.
549 CommonWebContentsDelegate::HandleKeyboardEvent(source, event);
553 bool WebContents::PreHandleKeyboardEvent(
554 content::WebContents* source,
555 const content::NativeWebKeyboardEvent& event,
556 bool* is_keyboard_shortcut) {
557 if (event.type == blink::WebInputEvent::Type::RawKeyDown
558 || event.type == blink::WebInputEvent::Type::KeyUp)
559 return Emit("before-input-event", event);
564 void WebContents::EnterFullscreenModeForTab(content::WebContents* source,
565 const GURL& origin) {
566 auto permission_helper =
567 WebContentsPermissionHelper::FromWebContents(source);
568 auto callback = base::Bind(&WebContents::OnEnterFullscreenModeForTab,
569 base::Unretained(this), source, origin);
570 permission_helper->RequestFullscreenPermission(callback);
573 void WebContents::OnEnterFullscreenModeForTab(content::WebContents* source,
578 CommonWebContentsDelegate::EnterFullscreenModeForTab(source, origin);
579 Emit("enter-html-full-screen");
582 void WebContents::ExitFullscreenModeForTab(content::WebContents* source) {
583 CommonWebContentsDelegate::ExitFullscreenModeForTab(source);
584 Emit("leave-html-full-screen");
587 void WebContents::RendererUnresponsive(
588 content::WebContents* source,
589 const content::WebContentsUnresponsiveState& unresponsive_state) {
590 Emit("unresponsive");
591 if ((type_ == BROWSER_WINDOW || type_ == OFF_SCREEN) && owner_window())
592 owner_window()->RendererUnresponsive(source);
595 void WebContents::RendererResponsive(content::WebContents* source) {
597 if ((type_ == BROWSER_WINDOW || type_ == OFF_SCREEN) && owner_window())
598 owner_window()->RendererResponsive(source);
601 bool WebContents::HandleContextMenu(const content::ContextMenuParams& params) {
602 if (params.custom_context.is_pepper_menu) {
603 Emit("pepper-context-menu", std::make_pair(params, web_contents()));
604 web_contents()->NotifyContextMenuClosed(params.custom_context);
606 Emit("context-menu", std::make_pair(params, web_contents()));
612 bool WebContents::OnGoToEntryOffset(int offset) {
617 void WebContents::FindReply(content::WebContents* web_contents,
619 int number_of_matches,
620 const gfx::Rect& selection_rect,
621 int active_match_ordinal,
626 v8::Locker locker(isolate());
627 v8::HandleScope handle_scope(isolate());
628 mate::Dictionary result = mate::Dictionary::CreateEmpty(isolate());
629 result.Set("requestId", request_id);
630 result.Set("matches", number_of_matches);
631 result.Set("selectionArea", selection_rect);
632 result.Set("activeMatchOrdinal", active_match_ordinal);
633 result.Set("finalUpdate", final_update); // Deprecate after 2.0
634 Emit("found-in-page", result);
637 bool WebContents::CheckMediaAccessPermission(
638 content::WebContents* web_contents,
639 const GURL& security_origin,
640 content::MediaStreamType type) {
644 void WebContents::RequestMediaAccessPermission(
645 content::WebContents* web_contents,
646 const content::MediaStreamRequest& request,
647 const content::MediaResponseCallback& callback) {
648 auto permission_helper =
649 WebContentsPermissionHelper::FromWebContents(web_contents);
650 permission_helper->RequestMediaAccessPermission(request, callback);
653 void WebContents::RequestToLockMouse(
654 content::WebContents* web_contents,
656 bool last_unlocked_by_target) {
657 auto permission_helper =
658 WebContentsPermissionHelper::FromWebContents(web_contents);
659 permission_helper->RequestPointerLockPermission(user_gesture);
662 std::unique_ptr<content::BluetoothChooser> WebContents::RunBluetoothChooser(
663 content::RenderFrameHost* frame,
664 const content::BluetoothChooser::EventHandler& event_handler) {
665 std::unique_ptr<BluetoothChooser> bluetooth_chooser(
666 new BluetoothChooser(this, event_handler));
667 return std::move(bluetooth_chooser);
670 void WebContents::BeforeUnloadFired(const base::TimeTicks& proceed_time) {
671 // Do nothing, we override this method just to avoid compilation error since
672 // there are two virtual functions named BeforeUnloadFired.
675 void WebContents::RenderViewCreated(content::RenderViewHost* render_view_host) {
676 const auto impl = content::RenderWidgetHostImpl::FromID(
677 render_view_host->GetProcess()->GetID(),
678 render_view_host->GetRoutingID());
680 impl->disable_hidden_ = !background_throttling_;
683 void WebContents::RenderViewDeleted(content::RenderViewHost* render_view_host) {
684 Emit("render-view-deleted", render_view_host->GetProcess()->GetID());
687 void WebContents::RenderProcessGone(base::TerminationStatus status) {
688 Emit("crashed", status == base::TERMINATION_STATUS_PROCESS_WAS_KILLED);
691 void WebContents::PluginCrashed(const base::FilePath& plugin_path,
692 base::ProcessId plugin_pid) {
693 content::WebPluginInfo info;
694 auto plugin_service = content::PluginService::GetInstance();
695 plugin_service->GetPluginInfoByPath(plugin_path, &info);
696 Emit("plugin-crashed", info.name, info.version);
699 void WebContents::MediaStartedPlaying(const MediaPlayerInfo& video_type,
700 const MediaPlayerId& id) {
701 Emit("media-started-playing");
704 void WebContents::MediaStoppedPlaying(const MediaPlayerInfo& video_type,
705 const MediaPlayerId& id) {
706 Emit("media-paused");
709 void WebContents::DidChangeThemeColor(SkColor theme_color) {
710 Emit("did-change-theme-color", atom::ToRGBHex(theme_color));
713 void WebContents::DocumentLoadedInFrame(
714 content::RenderFrameHost* render_frame_host) {
715 if (!render_frame_host->GetParent())
719 void WebContents::DidFinishLoad(content::RenderFrameHost* render_frame_host,
720 const GURL& validated_url) {
721 bool is_main_frame = !render_frame_host->GetParent();
722 Emit("did-frame-finish-load", is_main_frame);
725 Emit("did-finish-load");
728 void WebContents::DidFailLoad(content::RenderFrameHost* render_frame_host,
731 const base::string16& error_description,
732 bool was_ignored_by_handler) {
733 bool is_main_frame = !render_frame_host->GetParent();
734 Emit("did-fail-load", error_code, error_description, url, is_main_frame);
737 void WebContents::DidStartLoading() {
738 Emit("did-start-loading");
741 void WebContents::DidStopLoading() {
742 Emit("did-stop-loading");
745 void WebContents::DidGetResourceResponseStart(
746 const content::ResourceRequestDetails& details) {
747 Emit("did-get-response-details",
748 details.socket_address.IsEmpty(),
750 details.original_url,
751 details.http_response_code,
754 details.headers.get(),
755 ResourceTypeToString(details.resource_type));
758 void WebContents::DidGetRedirectForResourceRequest(
759 const content::ResourceRedirectDetails& details) {
760 Emit("did-get-redirect-request",
763 (details.resource_type == content::RESOURCE_TYPE_MAIN_FRAME),
764 details.http_response_code,
767 details.headers.get());
770 void WebContents::DidStartNavigation(
771 content::NavigationHandle* navigation_handle) {
772 if (!navigation_handle->IsInMainFrame() || navigation_handle->IsSamePage())
775 if (deferred_load_url_.id) {
776 auto web_contents = navigation_handle->GetWebContents();
777 auto& controller = web_contents->GetController();
778 int id = controller.GetPendingEntry()->GetUniqueID();
779 if (id == deferred_load_url_.id) {
780 if (!deferred_load_url_.params.url.is_empty()) {
781 auto params = deferred_load_url_.params;
782 deferred_load_url_.id = 0;
783 deferred_load_url_.params =
784 content::NavigationController::LoadURLParams(GURL());
785 controller.LoadURLWithParams(params);
786 SetBackgroundColor(web_contents);
788 deferred_load_url_.id = 0;
794 void WebContents::DidFinishNavigation(
795 content::NavigationHandle* navigation_handle) {
796 bool is_main_frame = navigation_handle->IsInMainFrame();
797 if (navigation_handle->HasCommitted() && !navigation_handle->IsErrorPage()) {
798 auto url = navigation_handle->GetURL();
799 bool is_in_page = navigation_handle->IsSamePage();
800 if (is_main_frame && !is_in_page) {
801 Emit("did-navigate", url);
802 } else if (is_in_page) {
803 Emit("did-navigate-in-page", url, is_main_frame);
806 auto url = navigation_handle->GetURL();
807 int code = navigation_handle->GetNetErrorCode();
808 auto description = net::ErrorToShortString(code);
809 Emit("did-fail-provisional-load", code, description, url, is_main_frame);
811 // Do not emit "did-fail-load" for canceled requests.
812 if (code != net::ERR_ABORTED)
813 Emit("did-fail-load", code, description, url, is_main_frame);
817 void WebContents::TitleWasSet(content::NavigationEntry* entry,
820 Emit("-page-title-updated", entry->GetTitle(), explicit_set);
822 Emit("-page-title-updated", "", explicit_set);
825 void WebContents::DidUpdateFaviconURL(
826 const std::vector<content::FaviconURL>& urls) {
827 std::set<GURL> unique_urls;
828 for (const auto& iter : urls) {
829 if (iter.icon_type != content::FaviconURL::FAVICON)
831 const GURL& url = iter.icon_url;
833 unique_urls.insert(url);
835 Emit("page-favicon-updated", unique_urls);
838 void WebContents::Observe(int type,
839 const content::NotificationSource& source,
840 const content::NotificationDetails& details) {
842 case content::NOTIFICATION_NAV_ENTRY_PENDING: {
843 content::NavigationEntry* entry =
844 content::Details<content::NavigationEntry>(details).ptr();
845 content::NavigationEntryImpl* entry_impl =
846 static_cast<content::NavigationEntryImpl*>(entry);
847 // In NavigatorImpl::DidStartMainFrameNavigation when there is no
848 // browser side pending entry available it creates a new one based
849 // on existing pending entry, hence we track the unique id here
850 // instead in WebContents::LoadURL with controller.GetPendingEntry()
851 // TODO(deepak1556): Remove once we have
852 // https://codereview.chromium.org/2661743002.
853 if (entry_impl->frame_tree_node_id() == -1) {
854 deferred_load_url_.id = entry->GetUniqueID();
864 void WebContents::DevToolsReloadPage() {
865 Emit("devtools-reload-page");
868 void WebContents::DevToolsFocused() {
869 Emit("devtools-focused");
872 void WebContents::DevToolsOpened() {
873 v8::Locker locker(isolate());
874 v8::HandleScope handle_scope(isolate());
875 auto handle = WebContents::CreateFrom(
876 isolate(), managed_web_contents()->GetDevToolsWebContents());
877 devtools_web_contents_.Reset(isolate(), handle.ToV8());
879 // Set inspected tabID.
880 base::FundamentalValue tab_id(ID());
881 managed_web_contents()->CallClientFunction(
882 "DevToolsAPI.setInspectedTabId", &tab_id, nullptr, nullptr);
884 // Inherit owner window in devtools.
886 handle->SetOwnerWindow(managed_web_contents()->GetDevToolsWebContents(),
889 Emit("devtools-opened");
892 void WebContents::DevToolsClosed() {
893 v8::Locker locker(isolate());
894 v8::HandleScope handle_scope(isolate());
895 devtools_web_contents_.Reset();
897 Emit("devtools-closed");
900 bool WebContents::OnMessageReceived(const IPC::Message& message) {
902 IPC_BEGIN_MESSAGE_MAP(WebContents, message)
903 IPC_MESSAGE_HANDLER(AtomViewHostMsg_Message, OnRendererMessage)
904 IPC_MESSAGE_HANDLER_DELAY_REPLY(AtomViewHostMsg_Message_Sync,
905 OnRendererMessageSync)
906 IPC_MESSAGE_HANDLER_DELAY_REPLY(AtomViewHostMsg_SetTemporaryZoomLevel,
907 OnSetTemporaryZoomLevel)
908 IPC_MESSAGE_HANDLER_DELAY_REPLY(AtomViewHostMsg_GetZoomLevel,
911 // FIXME: Disable OnCursorChange due to stach_chk_fail crash.
912 // IPC_MESSAGE_HANDLER_CODE(ViewHostMsg_SetCursor, OnCursorChange,
914 IPC_MESSAGE_UNHANDLED(handled = false)
915 IPC_END_MESSAGE_MAP()
920 // There are three ways of destroying a webContents:
921 // 1. call webContents.destroy();
922 // 2. garbage collection;
923 // 3. user closes the window of webContents;
924 // For webview only #1 will happen, for BrowserWindow both #1 and #3 may
925 // happen. The #2 should never happen for webContents, because webview is
926 // managed by GuestViewManager, and BrowserWindow's webContents is managed
928 // For #1, the destructor will do the cleanup work and we only need to make
929 // sure "destroyed" event is emitted. For #3, the content::WebContents will
930 // be destroyed on close, and WebContentsDestroyed would be called for it, so
931 // we need to make sure the api::WebContents is also deleted.
932 void WebContents::WebContentsDestroyed() {
933 // Cleanup relationships with other parts.
936 // We can not call Destroy here because we need to call Emit first, but we
937 // also do not want any method to be used, so just mark as destroyed here.
942 // Destroy the native class in next tick.
943 base::ThreadTaskRunnerHandle::Get()->PostTask(
944 FROM_HERE, GetDestroyClosure());
947 void WebContents::NavigationEntryCommitted(
948 const content::LoadCommittedDetails& details) {
949 Emit("navigation-entry-commited", details.entry->GetURL(),
950 details.is_in_page, details.did_replace_entry);
953 int64_t WebContents::GetID() const {
954 int64_t process_id = web_contents()->GetRenderProcessHost()->GetID();
955 int64_t routing_id = web_contents()->GetRoutingID();
956 int64_t rv = (process_id << 32) + routing_id;
960 int WebContents::GetProcessID() const {
961 return web_contents()->GetRenderProcessHost()->GetID();
964 WebContents::Type WebContents::GetType() const {
968 bool WebContents::Equal(const WebContents* web_contents) const {
969 return GetID() == web_contents->GetID();
972 void WebContents::LoadURL(const GURL& url, const mate::Dictionary& options) {
973 if (!url.is_valid() || url.spec().size() > url::kMaxURLChars) {
974 Emit("did-fail-load",
975 static_cast<int>(net::ERR_INVALID_URL),
976 net::ErrorToShortString(net::ERR_INVALID_URL),
977 url.possibly_invalid_spec(),
982 content::NavigationController::LoadURLParams params(url);
985 if (options.Get("httpReferrer", &http_referrer))
986 params.referrer = content::Referrer(http_referrer.GetAsReferrer(),
987 blink::WebReferrerPolicyDefault);
989 std::string user_agent;
990 if (options.Get("userAgent", &user_agent))
991 web_contents()->SetUserAgentOverride(user_agent);
993 std::string extra_headers;
994 if (options.Get("extraHeaders", &extra_headers))
995 params.extra_headers = extra_headers;
997 scoped_refptr<content::ResourceRequestBodyImpl> body;
998 if (options.Get("postData", &body)) {
999 params.post_data = body;
1000 params.load_type = content::NavigationController::LOAD_TYPE_HTTP_POST;
1003 GURL base_url_for_data_url;
1004 if (options.Get("baseURLForDataURL", &base_url_for_data_url)) {
1005 params.base_url_for_data_url = base_url_for_data_url;
1006 params.load_type = content::NavigationController::LOAD_TYPE_DATA;
1009 params.transition_type = ui::PAGE_TRANSITION_TYPED;
1010 params.should_clear_history_list = true;
1011 params.override_user_agent = content::NavigationController::UA_OVERRIDE_TRUE;
1013 if (deferred_load_url_.id) {
1014 deferred_load_url_.params = params;
1018 web_contents()->GetController().LoadURLWithParams(params);
1019 // We have to call it right after LoadURL because the RenderViewHost is only
1020 // created after loading a page.
1021 SetBackgroundColor(web_contents());
1024 void WebContents::DownloadURL(const GURL& url) {
1025 auto browser_context = web_contents()->GetBrowserContext();
1026 auto download_manager =
1027 content::BrowserContext::GetDownloadManager(browser_context);
1029 download_manager->DownloadUrl(
1030 content::DownloadUrlParameters::CreateForWebContentsMainFrame(
1031 web_contents(), url));
1034 GURL WebContents::GetURL() const {
1035 return web_contents()->GetURL();
1038 base::string16 WebContents::GetTitle() const {
1039 return web_contents()->GetTitle();
1042 bool WebContents::IsLoading() const {
1043 return web_contents()->IsLoading();
1046 bool WebContents::IsLoadingMainFrame() const {
1047 // Comparing site instances works because Electron always creates a new site
1048 // instance when navigating, regardless of origin. See AtomBrowserClient.
1049 return (web_contents()->GetLastCommittedURL().is_empty() ||
1050 web_contents()->GetSiteInstance() !=
1051 web_contents()->GetPendingSiteInstance()) && IsLoading();
1054 bool WebContents::IsWaitingForResponse() const {
1055 return web_contents()->IsWaitingForResponse();
1058 void WebContents::Stop() {
1059 web_contents()->Stop();
1062 void WebContents::GoBack() {
1063 atom::AtomBrowserClient::SuppressRendererProcessRestartForOnce();
1064 web_contents()->GetController().GoBack();
1067 void WebContents::GoForward() {
1068 atom::AtomBrowserClient::SuppressRendererProcessRestartForOnce();
1069 web_contents()->GetController().GoForward();
1072 void WebContents::GoToOffset(int offset) {
1073 atom::AtomBrowserClient::SuppressRendererProcessRestartForOnce();
1074 web_contents()->GetController().GoToOffset(offset);
1077 const std::string WebContents::GetWebRTCIPHandlingPolicy() const {
1078 return web_contents()->
1079 GetMutableRendererPrefs()->webrtc_ip_handling_policy;
1082 void WebContents::SetWebRTCIPHandlingPolicy(
1083 const std::string& webrtc_ip_handling_policy) {
1084 if (GetWebRTCIPHandlingPolicy() == webrtc_ip_handling_policy)
1086 web_contents()->GetMutableRendererPrefs()->webrtc_ip_handling_policy =
1087 webrtc_ip_handling_policy;
1089 content::RenderViewHost* host = web_contents()->GetRenderViewHost();
1091 host->SyncRendererPrefs();
1094 bool WebContents::IsCrashed() const {
1095 return web_contents()->IsCrashed();
1098 void WebContents::SetUserAgent(const std::string& user_agent,
1099 mate::Arguments* args) {
1100 web_contents()->SetUserAgentOverride(user_agent);
1103 std::string WebContents::GetUserAgent() {
1104 return web_contents()->GetUserAgentOverride();
1107 bool WebContents::SavePage(const base::FilePath& full_file_path,
1108 const content::SavePageType& save_type,
1109 const SavePageHandler::SavePageCallback& callback) {
1110 auto handler = new SavePageHandler(web_contents(), callback);
1111 return handler->Handle(full_file_path, save_type);
1114 void WebContents::OpenDevTools(mate::Arguments* args) {
1115 if (type_ == REMOTE)
1118 if (!enable_devtools_)
1122 if (type_ == WEB_VIEW || !owner_window()) {
1124 } else if (args && args->Length() == 1) {
1125 bool detach = false;
1126 mate::Dictionary options;
1127 if (args->GetNext(&options)) {
1128 options.Get("mode", &state);
1130 // TODO(kevinsawicki) Remove in 2.0
1131 options.Get("detach", &detach);
1132 if (state.empty() && detach)
1136 managed_web_contents()->SetDockState(state);
1137 managed_web_contents()->ShowDevTools();
1140 void WebContents::CloseDevTools() {
1141 if (type_ == REMOTE)
1144 managed_web_contents()->CloseDevTools();
1147 bool WebContents::IsDevToolsOpened() {
1148 if (type_ == REMOTE)
1151 return managed_web_contents()->IsDevToolsViewShowing();
1154 bool WebContents::IsDevToolsFocused() {
1155 if (type_ == REMOTE)
1158 return managed_web_contents()->GetView()->IsDevToolsViewFocused();
1161 void WebContents::EnableDeviceEmulation(
1162 const blink::WebDeviceEmulationParams& params) {
1163 if (type_ == REMOTE)
1166 Send(new ViewMsg_EnableDeviceEmulation(routing_id(), params));
1169 void WebContents::DisableDeviceEmulation() {
1170 if (type_ == REMOTE)
1173 Send(new ViewMsg_DisableDeviceEmulation(routing_id()));
1176 void WebContents::ToggleDevTools() {
1177 if (IsDevToolsOpened())
1180 OpenDevTools(nullptr);
1183 void WebContents::InspectElement(int x, int y) {
1184 if (type_ == REMOTE)
1187 if (!enable_devtools_)
1190 if (!managed_web_contents()->GetDevToolsWebContents())
1191 OpenDevTools(nullptr);
1192 managed_web_contents()->InspectElement(x, y);
1195 void WebContents::InspectServiceWorker() {
1196 if (type_ == REMOTE)
1199 if (!enable_devtools_)
1202 for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) {
1203 if (agent_host->GetType() ==
1204 content::DevToolsAgentHost::kTypeServiceWorker) {
1205 OpenDevTools(nullptr);
1206 managed_web_contents()->AttachTo(agent_host);
1212 void WebContents::HasServiceWorker(
1213 const base::Callback<void(bool)>& callback) {
1214 auto context = GetServiceWorkerContext(web_contents());
1218 context->CheckHasServiceWorker(web_contents()->GetLastCommittedURL(),
1223 void WebContents::UnregisterServiceWorker(
1224 const base::Callback<void(bool)>& callback) {
1225 auto context = GetServiceWorkerContext(web_contents());
1229 context->UnregisterServiceWorker(web_contents()->GetLastCommittedURL(),
1233 void WebContents::SetAudioMuted(bool muted) {
1234 web_contents()->SetAudioMuted(muted);
1237 bool WebContents::IsAudioMuted() {
1238 return web_contents()->IsAudioMuted();
1241 void WebContents::Print(mate::Arguments* args) {
1242 PrintSettings settings = { false, false };
1243 if (args->Length() == 1 && !args->GetNext(&settings)) {
1248 printing::PrintViewManagerBasic::FromWebContents(web_contents())->
1249 PrintNow(web_contents()->GetMainFrame(),
1251 settings.print_background);
1254 void WebContents::PrintToPDF(const base::DictionaryValue& setting,
1255 const PrintToPDFCallback& callback) {
1256 printing::PrintPreviewMessageHandler::FromWebContents(web_contents())->
1257 PrintToPDF(setting, callback);
1260 void WebContents::AddWorkSpace(mate::Arguments* args,
1261 const base::FilePath& path) {
1263 args->ThrowError("path cannot be empty");
1266 DevToolsAddFileSystem(path);
1269 void WebContents::RemoveWorkSpace(mate::Arguments* args,
1270 const base::FilePath& path) {
1272 args->ThrowError("path cannot be empty");
1275 DevToolsRemoveFileSystem(path);
1278 void WebContents::Undo() {
1279 web_contents()->Undo();
1282 void WebContents::Redo() {
1283 web_contents()->Redo();
1286 void WebContents::Cut() {
1287 web_contents()->Cut();
1290 void WebContents::Copy() {
1291 web_contents()->Copy();
1294 void WebContents::Paste() {
1295 web_contents()->Paste();
1298 void WebContents::PasteAndMatchStyle() {
1299 web_contents()->PasteAndMatchStyle();
1302 void WebContents::Delete() {
1303 web_contents()->Delete();
1306 void WebContents::SelectAll() {
1307 web_contents()->SelectAll();
1310 void WebContents::Unselect() {
1311 web_contents()->Unselect();
1314 void WebContents::Replace(const base::string16& word) {
1315 web_contents()->Replace(word);
1318 void WebContents::ReplaceMisspelling(const base::string16& word) {
1319 web_contents()->ReplaceMisspelling(word);
1322 uint32_t WebContents::FindInPage(mate::Arguments* args) {
1323 uint32_t request_id = GetNextRequestId();
1324 base::string16 search_text;
1325 blink::WebFindOptions options;
1326 if (!args->GetNext(&search_text) || search_text.empty()) {
1327 args->ThrowError("Must provide a non-empty search content");
1331 args->GetNext(&options);
1333 web_contents()->Find(request_id, search_text, options);
1337 void WebContents::StopFindInPage(content::StopFindAction action) {
1338 web_contents()->StopFinding(action);
1341 void WebContents::ShowDefinitionForSelection() {
1342 #if defined(OS_MACOSX)
1343 const auto view = web_contents()->GetRenderWidgetHostView();
1345 view->ShowDefinitionForSelection();
1349 void WebContents::CopyImageAt(int x, int y) {
1350 const auto host = web_contents()->GetMainFrame();
1352 host->CopyImageAt(x, y);
1355 void WebContents::Focus() {
1356 web_contents()->Focus();
1359 #if !defined(OS_MACOSX)
1360 bool WebContents::IsFocused() const {
1361 auto view = web_contents()->GetRenderWidgetHostView();
1362 if (!view) return false;
1364 #if defined(USE_EFL)
1367 if (GetType() != BACKGROUND_PAGE) {
1368 auto window = web_contents()->GetNativeView()->GetToplevelWindow();
1369 if (window && !window->IsVisible())
1374 return view->HasFocus();
1378 void WebContents::TabTraverse(bool reverse) {
1379 web_contents()->FocusThroughTabTraversal(reverse);
1382 bool WebContents::SendIPCMessage(bool all_frames,
1383 const base::string16& channel,
1384 const base::ListValue& args) {
1385 return Send(new AtomViewMsg_Message(routing_id(), all_frames, channel, args));
1388 void WebContents::SendInputEvent(v8::Isolate* isolate,
1389 v8::Local<v8::Value> input_event) {
1390 const auto view = web_contents()->GetRenderWidgetHostView();
1393 const auto host = view->GetRenderWidgetHost();
1397 int type = mate::GetWebInputEventType(isolate, input_event);
1398 if (blink::WebInputEvent::isMouseEventType(type)) {
1399 blink::WebMouseEvent mouse_event;
1400 if (mate::ConvertFromV8(isolate, input_event, &mouse_event)) {
1401 host->ForwardMouseEvent(mouse_event);
1404 } else if (blink::WebInputEvent::isKeyboardEventType(type)) {
1405 content::NativeWebKeyboardEvent keyboard_event;
1406 if (mate::ConvertFromV8(isolate, input_event, &keyboard_event)) {
1407 host->ForwardKeyboardEvent(keyboard_event);
1410 } else if (type == blink::WebInputEvent::MouseWheel) {
1411 blink::WebMouseWheelEvent mouse_wheel_event;
1412 if (mate::ConvertFromV8(isolate, input_event, &mouse_wheel_event)) {
1413 host->ForwardWheelEvent(mouse_wheel_event);
1418 isolate->ThrowException(v8::Exception::Error(mate::StringToV8(
1419 isolate, "Invalid event object")));
1422 void WebContents::BeginFrameSubscription(mate::Arguments* args) {
1423 bool only_dirty = false;
1424 FrameSubscriber::FrameCaptureCallback callback;
1426 args->GetNext(&only_dirty);
1427 if (!args->GetNext(&callback)) {
1432 const auto view = web_contents()->GetRenderWidgetHostView();
1434 std::unique_ptr<FrameSubscriber> frame_subscriber(new FrameSubscriber(
1435 isolate(), view, callback, only_dirty));
1436 view->BeginFrameSubscription(std::move(frame_subscriber));
1440 void WebContents::EndFrameSubscription() {
1441 const auto view = web_contents()->GetRenderWidgetHostView();
1443 view->EndFrameSubscription();
1446 void WebContents::StartDrag(const mate::Dictionary& item,
1447 mate::Arguments* args) {
1448 base::FilePath file;
1449 std::vector<base::FilePath> files;
1450 if (!item.Get("files", &files) && item.Get("file", &file)) {
1451 files.push_back(file);
1454 mate::Handle<NativeImage> icon;
1455 if (!item.Get("icon", &icon) && !file.empty()) {
1456 // TODO(zcbenz): Set default icon from file.
1460 if (icon.IsEmpty()) {
1461 args->ThrowError("Must specify 'icon' option");
1465 #if defined(OS_MACOSX)
1466 // NSWindow.dragImage requires a non-empty NSImage
1467 if (icon->image().IsEmpty()) {
1468 args->ThrowError("Must specify non-empty 'icon' option");
1474 if (!files.empty()) {
1475 base::MessageLoop::ScopedNestableTaskAllower allow(
1476 base::MessageLoop::current());
1477 DragFileItems(files, icon->image(), web_contents()->GetNativeView());
1479 args->ThrowError("Must specify either 'file' or 'files' option");
1483 void WebContents::CapturePage(mate::Arguments* args) {
1485 base::Callback<void(const gfx::Image&)> callback;
1487 if (!(args->Length() == 1 && args->GetNext(&callback)) &&
1488 !(args->Length() == 2 && args->GetNext(&rect)
1489 && args->GetNext(&callback))) {
1494 const auto view = web_contents()->GetRenderWidgetHostView();
1495 const auto host = view ? view->GetRenderWidgetHost() : nullptr;
1496 if (!view || !host) {
1497 callback.Run(gfx::Image());
1501 // Capture full page if user doesn't specify a |rect|.
1502 const gfx::Size view_size = rect.IsEmpty() ? view->GetViewBounds().size() :
1505 // By default, the requested bitmap size is the view size in screen
1506 // coordinates. However, if there's more pixel detail available on the
1507 // current system, increase the requested bitmap size to capture it all.
1508 gfx::Size bitmap_size = view_size;
1509 const gfx::NativeView native_view = view->GetNativeView();
1511 display::Screen::GetScreen()->GetDisplayNearestWindow(native_view)
1512 .device_scale_factor();
1514 bitmap_size = gfx::ScaleToCeiledSize(view_size, scale);
1516 host->CopyFromBackingStore(gfx::Rect(rect.origin(), view_size),
1518 base::Bind(&OnCapturePageDone, callback),
1519 kBGRA_8888_SkColorType);
1522 void WebContents::OnCursorChange(const content::WebCursor& cursor) {
1523 content::WebCursor::CursorInfo info;
1524 cursor.GetCursorInfo(&info);
1526 if (cursor.IsCustom()) {
1527 Emit("cursor-changed", CursorTypeToString(info),
1528 gfx::Image::CreateFrom1xBitmap(info.custom_image),
1529 info.image_scale_factor,
1530 gfx::Size(info.custom_image.width(), info.custom_image.height()),
1533 Emit("cursor-changed", CursorTypeToString(info));
1537 void WebContents::SetSize(const SetSizeParams& params) {
1538 if (guest_delegate_)
1539 guest_delegate_->SetSize(params);
1542 bool WebContents::IsGuest() const {
1543 return type_ == WEB_VIEW;
1546 bool WebContents::IsOffScreen() const {
1547 return type_ == OFF_SCREEN;
1550 void WebContents::OnPaint(const gfx::Rect& dirty_rect, const SkBitmap& bitmap) {
1551 mate::Handle<NativeImage> image =
1552 NativeImage::Create(isolate(), gfx::Image::CreateFrom1xBitmap(bitmap));
1553 Emit("paint", dirty_rect, image);
1556 void WebContents::StartPainting() {
1560 auto* osr_rwhv = static_cast<OffScreenRenderWidgetHostView*>(
1561 web_contents()->GetRenderWidgetHostView());
1563 osr_rwhv->SetPainting(true);
1566 void WebContents::StopPainting() {
1570 auto* osr_rwhv = static_cast<OffScreenRenderWidgetHostView*>(
1571 web_contents()->GetRenderWidgetHostView());
1573 osr_rwhv->SetPainting(false);
1576 bool WebContents::IsPainting() const {
1580 const auto* osr_rwhv = static_cast<OffScreenRenderWidgetHostView*>(
1581 web_contents()->GetRenderWidgetHostView());
1582 return osr_rwhv && osr_rwhv->IsPainting();
1585 void WebContents::SetFrameRate(int frame_rate) {
1589 auto* osr_rwhv = static_cast<OffScreenRenderWidgetHostView*>(
1590 web_contents()->GetRenderWidgetHostView());
1592 osr_rwhv->SetFrameRate(frame_rate);
1595 int WebContents::GetFrameRate() const {
1599 const auto* osr_rwhv = static_cast<OffScreenRenderWidgetHostView*>(
1600 web_contents()->GetRenderWidgetHostView());
1601 return osr_rwhv ? osr_rwhv->GetFrameRate() : 0;
1604 void WebContents::Invalidate() {
1605 if (IsOffScreen()) {
1606 auto* osr_rwhv = static_cast<OffScreenRenderWidgetHostView*>(
1607 web_contents()->GetRenderWidgetHostView());
1609 osr_rwhv->Invalidate();
1611 const auto window = owner_window();
1613 window->Invalidate();
1617 void WebContents::SetZoomLevel(double level) {
1618 zoom_controller_->SetZoomLevel(level);
1621 double WebContents::GetZoomLevel() {
1622 return zoom_controller_->GetZoomLevel();
1625 void WebContents::SetZoomFactor(double factor) {
1626 auto level = content::ZoomFactorToZoomLevel(factor);
1627 SetZoomLevel(level);
1630 double WebContents::GetZoomFactor() {
1631 auto level = GetZoomLevel();
1632 return content::ZoomLevelToZoomFactor(level);
1635 void WebContents::OnSetTemporaryZoomLevel(double level,
1636 IPC::Message* reply_msg) {
1637 zoom_controller_->SetTemporaryZoomLevel(level);
1638 double new_level = zoom_controller_->GetZoomLevel();
1639 AtomViewHostMsg_SetTemporaryZoomLevel::WriteReplyParams(reply_msg, new_level);
1643 void WebContents::OnGetZoomLevel(IPC::Message* reply_msg) {
1644 AtomViewHostMsg_GetZoomLevel::WriteReplyParams(reply_msg, GetZoomLevel());
1648 v8::Local<v8::Value> WebContents::GetWebPreferences(v8::Isolate* isolate) {
1649 WebContentsPreferences* web_preferences =
1650 WebContentsPreferences::FromWebContents(web_contents());
1651 return mate::ConvertToV8(isolate, *web_preferences->web_preferences());
1654 v8::Local<v8::Value> WebContents::GetOwnerBrowserWindow() {
1656 return Window::From(isolate(), owner_window());
1658 return v8::Null(isolate());
1661 int32_t WebContents::ID() const {
1662 return weak_map_id();
1665 v8::Local<v8::Value> WebContents::Session(v8::Isolate* isolate) {
1666 return v8::Local<v8::Value>::New(isolate, session_);
1669 content::WebContents* WebContents::HostWebContents() {
1672 return embedder_->web_contents();
1675 void WebContents::SetEmbedder(const WebContents* embedder) {
1677 NativeWindow* owner_window = nullptr;
1678 auto relay = NativeWindowRelay::FromWebContents(embedder->web_contents());
1680 owner_window = relay->window.get();
1683 SetOwnerWindow(owner_window);
1685 content::RenderWidgetHostView* rwhv =
1686 web_contents()->GetRenderWidgetHostView();
1694 v8::Local<v8::Value> WebContents::DevToolsWebContents(v8::Isolate* isolate) {
1695 if (devtools_web_contents_.IsEmpty())
1696 return v8::Null(isolate);
1698 return v8::Local<v8::Value>::New(isolate, devtools_web_contents_);
1701 v8::Local<v8::Value> WebContents::Debugger(v8::Isolate* isolate) {
1702 if (debugger_.IsEmpty()) {
1703 auto handle = atom::api::Debugger::Create(isolate, web_contents());
1704 debugger_.Reset(isolate, handle.ToV8());
1706 return v8::Local<v8::Value>::New(isolate, debugger_);
1710 void WebContents::BuildPrototype(v8::Isolate* isolate,
1711 v8::Local<v8::FunctionTemplate> prototype) {
1712 prototype->SetClassName(mate::StringToV8(isolate, "WebContents"));
1713 mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
1715 .SetMethod("getId", &WebContents::GetID)
1716 .SetMethod("getProcessId", &WebContents::GetProcessID)
1717 .SetMethod("equal", &WebContents::Equal)
1718 .SetMethod("_loadURL", &WebContents::LoadURL)
1719 .SetMethod("downloadURL", &WebContents::DownloadURL)
1720 .SetMethod("_getURL", &WebContents::GetURL)
1721 .SetMethod("getTitle", &WebContents::GetTitle)
1722 .SetMethod("isLoading", &WebContents::IsLoading)
1723 .SetMethod("isLoadingMainFrame", &WebContents::IsLoadingMainFrame)
1724 .SetMethod("isWaitingForResponse", &WebContents::IsWaitingForResponse)
1725 .SetMethod("_stop", &WebContents::Stop)
1726 .SetMethod("_goBack", &WebContents::GoBack)
1727 .SetMethod("_goForward", &WebContents::GoForward)
1728 .SetMethod("_goToOffset", &WebContents::GoToOffset)
1729 .SetMethod("isCrashed", &WebContents::IsCrashed)
1730 .SetMethod("setUserAgent", &WebContents::SetUserAgent)
1731 .SetMethod("getUserAgent", &WebContents::GetUserAgent)
1732 .SetMethod("savePage", &WebContents::SavePage)
1733 .SetMethod("openDevTools", &WebContents::OpenDevTools)
1734 .SetMethod("closeDevTools", &WebContents::CloseDevTools)
1735 .SetMethod("isDevToolsOpened", &WebContents::IsDevToolsOpened)
1736 .SetMethod("isDevToolsFocused", &WebContents::IsDevToolsFocused)
1737 .SetMethod("enableDeviceEmulation",
1738 &WebContents::EnableDeviceEmulation)
1739 .SetMethod("disableDeviceEmulation",
1740 &WebContents::DisableDeviceEmulation)
1741 .SetMethod("toggleDevTools", &WebContents::ToggleDevTools)
1742 .SetMethod("inspectElement", &WebContents::InspectElement)
1743 .SetMethod("setAudioMuted", &WebContents::SetAudioMuted)
1744 .SetMethod("isAudioMuted", &WebContents::IsAudioMuted)
1745 .SetMethod("undo", &WebContents::Undo)
1746 .SetMethod("redo", &WebContents::Redo)
1747 .SetMethod("cut", &WebContents::Cut)
1748 .SetMethod("copy", &WebContents::Copy)
1749 .SetMethod("paste", &WebContents::Paste)
1750 .SetMethod("pasteAndMatchStyle", &WebContents::PasteAndMatchStyle)
1751 .SetMethod("delete", &WebContents::Delete)
1752 .SetMethod("selectAll", &WebContents::SelectAll)
1753 .SetMethod("unselect", &WebContents::Unselect)
1754 .SetMethod("replace", &WebContents::Replace)
1755 .SetMethod("replaceMisspelling", &WebContents::ReplaceMisspelling)
1756 .SetMethod("findInPage", &WebContents::FindInPage)
1757 .SetMethod("stopFindInPage", &WebContents::StopFindInPage)
1758 .SetMethod("focus", &WebContents::Focus)
1759 .SetMethod("isFocused", &WebContents::IsFocused)
1760 .SetMethod("tabTraverse", &WebContents::TabTraverse)
1761 .SetMethod("_send", &WebContents::SendIPCMessage)
1762 .SetMethod("sendInputEvent", &WebContents::SendInputEvent)
1763 .SetMethod("beginFrameSubscription",
1764 &WebContents::BeginFrameSubscription)
1765 .SetMethod("endFrameSubscription", &WebContents::EndFrameSubscription)
1766 .SetMethod("startDrag", &WebContents::StartDrag)
1767 .SetMethod("setSize", &WebContents::SetSize)
1768 .SetMethod("isGuest", &WebContents::IsGuest)
1769 .SetMethod("isOffscreen", &WebContents::IsOffScreen)
1770 .SetMethod("startPainting", &WebContents::StartPainting)
1771 .SetMethod("stopPainting", &WebContents::StopPainting)
1772 .SetMethod("isPainting", &WebContents::IsPainting)
1773 .SetMethod("setFrameRate", &WebContents::SetFrameRate)
1774 .SetMethod("getFrameRate", &WebContents::GetFrameRate)
1775 .SetMethod("invalidate", &WebContents::Invalidate)
1776 .SetMethod("setZoomLevel", &WebContents::SetZoomLevel)
1777 .SetMethod("_getZoomLevel", &WebContents::GetZoomLevel)
1778 .SetMethod("setZoomFactor", &WebContents::SetZoomFactor)
1779 .SetMethod("_getZoomFactor", &WebContents::GetZoomFactor)
1780 .SetMethod("getType", &WebContents::GetType)
1781 .SetMethod("getWebPreferences", &WebContents::GetWebPreferences)
1782 .SetMethod("getOwnerBrowserWindow", &WebContents::GetOwnerBrowserWindow)
1783 .SetMethod("hasServiceWorker", &WebContents::HasServiceWorker)
1784 .SetMethod("unregisterServiceWorker",
1785 &WebContents::UnregisterServiceWorker)
1786 .SetMethod("inspectServiceWorker", &WebContents::InspectServiceWorker)
1787 .SetMethod("print", &WebContents::Print)
1788 .SetMethod("_printToPDF", &WebContents::PrintToPDF)
1789 .SetMethod("addWorkSpace", &WebContents::AddWorkSpace)
1790 .SetMethod("removeWorkSpace", &WebContents::RemoveWorkSpace)
1791 .SetMethod("showDefinitionForSelection",
1792 &WebContents::ShowDefinitionForSelection)
1793 .SetMethod("copyImageAt", &WebContents::CopyImageAt)
1794 .SetMethod("capturePage", &WebContents::CapturePage)
1795 .SetMethod("setEmbedder", &WebContents::SetEmbedder)
1796 .SetMethod("setWebRTCIPHandlingPolicy",
1797 &WebContents::SetWebRTCIPHandlingPolicy)
1798 .SetMethod("getWebRTCIPHandlingPolicy",
1799 &WebContents::GetWebRTCIPHandlingPolicy)
1800 .SetProperty("id", &WebContents::ID)
1801 .SetProperty("session", &WebContents::Session)
1802 .SetProperty("hostWebContents", &WebContents::HostWebContents)
1803 .SetProperty("devToolsWebContents", &WebContents::DevToolsWebContents)
1804 .SetProperty("debugger", &WebContents::Debugger);
1807 AtomBrowserContext* WebContents::GetBrowserContext() const {
1808 return static_cast<AtomBrowserContext*>(web_contents()->GetBrowserContext());
1811 void WebContents::OnRendererMessage(const base::string16& channel,
1812 const base::ListValue& args) {
1813 // webContents.emit(channel, new Event(), args...);
1814 Emit(base::UTF16ToUTF8(channel), args);
1817 void WebContents::OnRendererMessageSync(const base::string16& channel,
1818 const base::ListValue& args,
1819 IPC::Message* message) {
1820 // webContents.emit(channel, new Event(sender, message), args...);
1821 EmitWithSender(base::UTF16ToUTF8(channel), web_contents(), message, args);
1825 mate::Handle<WebContents> WebContents::CreateFrom(
1826 v8::Isolate* isolate, content::WebContents* web_contents) {
1827 // We have an existing WebContents object in JS.
1828 auto existing = TrackableObject::FromWrappedClass(isolate, web_contents);
1830 return mate::CreateHandle(isolate, static_cast<WebContents*>(existing));
1832 // Otherwise create a new WebContents wrapper object.
1833 return mate::CreateHandle(isolate, new WebContents(isolate, web_contents,
1837 mate::Handle<WebContents> WebContents::CreateFrom(
1838 v8::Isolate* isolate, content::WebContents* web_contents, Type type) {
1839 // Otherwise create a new WebContents wrapper object.
1840 return mate::CreateHandle(isolate, new WebContents(isolate, web_contents,
1845 mate::Handle<WebContents> WebContents::Create(
1846 v8::Isolate* isolate, const mate::Dictionary& options) {
1847 return mate::CreateHandle(isolate, new WebContents(isolate, options));
1856 using atom::api::WebContents;
1858 void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused,
1859 v8::Local<v8::Context> context, void* priv) {
1860 v8::Isolate* isolate = context->GetIsolate();
1861 mate::Dictionary dict(isolate, exports);
1862 dict.Set("WebContents", WebContents::GetConstructor(isolate)->GetFunction());
1863 dict.SetMethod("create", &WebContents::Create);
1864 dict.SetMethod("fromId", &mate::TrackableObject<WebContents>::FromWeakMapID);
1865 dict.SetMethod("getAllWebContents",
1866 &mate::TrackableObject<WebContents>::GetAll);
1871 NODE_MODULE_CONTEXT_AWARE_BUILTIN(atom_browser_web_contents, Initialize)