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)
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,
910 IPC_MESSAGE_HANDLER_CODE(ViewHostMsg_SetCursor, OnCursorChange,
912 IPC_MESSAGE_UNHANDLED(handled = false)
913 IPC_END_MESSAGE_MAP()
918 // There are three ways of destroying a webContents:
919 // 1. call webContents.destroy();
920 // 2. garbage collection;
921 // 3. user closes the window of webContents;
922 // For webview only #1 will happen, for BrowserWindow both #1 and #3 may
923 // happen. The #2 should never happen for webContents, because webview is
924 // managed by GuestViewManager, and BrowserWindow's webContents is managed
926 // For #1, the destructor will do the cleanup work and we only need to make
927 // sure "destroyed" event is emitted. For #3, the content::WebContents will
928 // be destroyed on close, and WebContentsDestroyed would be called for it, so
929 // we need to make sure the api::WebContents is also deleted.
930 void WebContents::WebContentsDestroyed() {
931 // Cleanup relationships with other parts.
934 // We can not call Destroy here because we need to call Emit first, but we
935 // also do not want any method to be used, so just mark as destroyed here.
940 // Destroy the native class in next tick.
941 base::ThreadTaskRunnerHandle::Get()->PostTask(
942 FROM_HERE, GetDestroyClosure());
945 void WebContents::NavigationEntryCommitted(
946 const content::LoadCommittedDetails& details) {
947 Emit("navigation-entry-commited", details.entry->GetURL(),
948 details.is_in_page, details.did_replace_entry);
951 int64_t WebContents::GetID() const {
952 int64_t process_id = web_contents()->GetRenderProcessHost()->GetID();
953 int64_t routing_id = web_contents()->GetRoutingID();
954 int64_t rv = (process_id << 32) + routing_id;
958 int WebContents::GetProcessID() const {
959 return web_contents()->GetRenderProcessHost()->GetID();
962 WebContents::Type WebContents::GetType() const {
966 bool WebContents::Equal(const WebContents* web_contents) const {
967 return GetID() == web_contents->GetID();
970 void WebContents::LoadURL(const GURL& url, const mate::Dictionary& options) {
971 if (!url.is_valid() || url.spec().size() > url::kMaxURLChars) {
972 Emit("did-fail-load",
973 static_cast<int>(net::ERR_INVALID_URL),
974 net::ErrorToShortString(net::ERR_INVALID_URL),
975 url.possibly_invalid_spec(),
980 content::NavigationController::LoadURLParams params(url);
983 if (options.Get("httpReferrer", &http_referrer))
984 params.referrer = content::Referrer(http_referrer.GetAsReferrer(),
985 blink::WebReferrerPolicyDefault);
987 std::string user_agent;
988 if (options.Get("userAgent", &user_agent))
989 web_contents()->SetUserAgentOverride(user_agent);
991 std::string extra_headers;
992 if (options.Get("extraHeaders", &extra_headers))
993 params.extra_headers = extra_headers;
995 scoped_refptr<content::ResourceRequestBodyImpl> body;
996 if (options.Get("postData", &body)) {
997 params.post_data = body;
998 params.load_type = content::NavigationController::LOAD_TYPE_HTTP_POST;
1001 GURL base_url_for_data_url;
1002 if (options.Get("baseURLForDataURL", &base_url_for_data_url)) {
1003 params.base_url_for_data_url = base_url_for_data_url;
1004 params.load_type = content::NavigationController::LOAD_TYPE_DATA;
1007 params.transition_type = ui::PAGE_TRANSITION_TYPED;
1008 params.should_clear_history_list = true;
1009 params.override_user_agent = content::NavigationController::UA_OVERRIDE_TRUE;
1011 if (deferred_load_url_.id) {
1012 deferred_load_url_.params = params;
1016 web_contents()->GetController().LoadURLWithParams(params);
1017 // We have to call it right after LoadURL because the RenderViewHost is only
1018 // created after loading a page.
1019 SetBackgroundColor(web_contents());
1022 void WebContents::DownloadURL(const GURL& url) {
1023 auto browser_context = web_contents()->GetBrowserContext();
1024 auto download_manager =
1025 content::BrowserContext::GetDownloadManager(browser_context);
1027 download_manager->DownloadUrl(
1028 content::DownloadUrlParameters::CreateForWebContentsMainFrame(
1029 web_contents(), url));
1032 GURL WebContents::GetURL() const {
1033 return web_contents()->GetURL();
1036 base::string16 WebContents::GetTitle() const {
1037 return web_contents()->GetTitle();
1040 bool WebContents::IsLoading() const {
1041 return web_contents()->IsLoading();
1044 bool WebContents::IsLoadingMainFrame() const {
1045 // Comparing site instances works because Electron always creates a new site
1046 // instance when navigating, regardless of origin. See AtomBrowserClient.
1047 return (web_contents()->GetLastCommittedURL().is_empty() ||
1048 web_contents()->GetSiteInstance() !=
1049 web_contents()->GetPendingSiteInstance()) && IsLoading();
1052 bool WebContents::IsWaitingForResponse() const {
1053 return web_contents()->IsWaitingForResponse();
1056 void WebContents::Stop() {
1057 web_contents()->Stop();
1060 void WebContents::GoBack() {
1061 atom::AtomBrowserClient::SuppressRendererProcessRestartForOnce();
1062 web_contents()->GetController().GoBack();
1065 void WebContents::GoForward() {
1066 atom::AtomBrowserClient::SuppressRendererProcessRestartForOnce();
1067 web_contents()->GetController().GoForward();
1070 void WebContents::GoToOffset(int offset) {
1071 atom::AtomBrowserClient::SuppressRendererProcessRestartForOnce();
1072 web_contents()->GetController().GoToOffset(offset);
1075 const std::string WebContents::GetWebRTCIPHandlingPolicy() const {
1076 return web_contents()->
1077 GetMutableRendererPrefs()->webrtc_ip_handling_policy;
1080 void WebContents::SetWebRTCIPHandlingPolicy(
1081 const std::string& webrtc_ip_handling_policy) {
1082 if (GetWebRTCIPHandlingPolicy() == webrtc_ip_handling_policy)
1084 web_contents()->GetMutableRendererPrefs()->webrtc_ip_handling_policy =
1085 webrtc_ip_handling_policy;
1087 content::RenderViewHost* host = web_contents()->GetRenderViewHost();
1089 host->SyncRendererPrefs();
1092 bool WebContents::IsCrashed() const {
1093 return web_contents()->IsCrashed();
1096 void WebContents::SetUserAgent(const std::string& user_agent,
1097 mate::Arguments* args) {
1098 web_contents()->SetUserAgentOverride(user_agent);
1101 std::string WebContents::GetUserAgent() {
1102 return web_contents()->GetUserAgentOverride();
1105 bool WebContents::SavePage(const base::FilePath& full_file_path,
1106 const content::SavePageType& save_type,
1107 const SavePageHandler::SavePageCallback& callback) {
1108 auto handler = new SavePageHandler(web_contents(), callback);
1109 return handler->Handle(full_file_path, save_type);
1112 void WebContents::OpenDevTools(mate::Arguments* args) {
1113 if (type_ == REMOTE)
1116 if (!enable_devtools_)
1120 if (type_ == WEB_VIEW || !owner_window()) {
1122 } else if (args && args->Length() == 1) {
1123 bool detach = false;
1124 mate::Dictionary options;
1125 if (args->GetNext(&options)) {
1126 options.Get("mode", &state);
1128 // TODO(kevinsawicki) Remove in 2.0
1129 options.Get("detach", &detach);
1130 if (state.empty() && detach)
1134 managed_web_contents()->SetDockState(state);
1135 managed_web_contents()->ShowDevTools();
1138 void WebContents::CloseDevTools() {
1139 if (type_ == REMOTE)
1142 managed_web_contents()->CloseDevTools();
1145 bool WebContents::IsDevToolsOpened() {
1146 if (type_ == REMOTE)
1149 return managed_web_contents()->IsDevToolsViewShowing();
1152 bool WebContents::IsDevToolsFocused() {
1153 if (type_ == REMOTE)
1156 return managed_web_contents()->GetView()->IsDevToolsViewFocused();
1159 void WebContents::EnableDeviceEmulation(
1160 const blink::WebDeviceEmulationParams& params) {
1161 if (type_ == REMOTE)
1164 Send(new ViewMsg_EnableDeviceEmulation(routing_id(), params));
1167 void WebContents::DisableDeviceEmulation() {
1168 if (type_ == REMOTE)
1171 Send(new ViewMsg_DisableDeviceEmulation(routing_id()));
1174 void WebContents::ToggleDevTools() {
1175 if (IsDevToolsOpened())
1178 OpenDevTools(nullptr);
1181 void WebContents::InspectElement(int x, int y) {
1182 if (type_ == REMOTE)
1185 if (!enable_devtools_)
1188 if (!managed_web_contents()->GetDevToolsWebContents())
1189 OpenDevTools(nullptr);
1190 managed_web_contents()->InspectElement(x, y);
1193 void WebContents::InspectServiceWorker() {
1194 if (type_ == REMOTE)
1197 if (!enable_devtools_)
1200 for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) {
1201 if (agent_host->GetType() ==
1202 content::DevToolsAgentHost::kTypeServiceWorker) {
1203 OpenDevTools(nullptr);
1204 managed_web_contents()->AttachTo(agent_host);
1210 void WebContents::HasServiceWorker(
1211 const base::Callback<void(bool)>& callback) {
1212 auto context = GetServiceWorkerContext(web_contents());
1216 context->CheckHasServiceWorker(web_contents()->GetLastCommittedURL(),
1221 void WebContents::UnregisterServiceWorker(
1222 const base::Callback<void(bool)>& callback) {
1223 auto context = GetServiceWorkerContext(web_contents());
1227 context->UnregisterServiceWorker(web_contents()->GetLastCommittedURL(),
1231 void WebContents::SetAudioMuted(bool muted) {
1232 web_contents()->SetAudioMuted(muted);
1235 bool WebContents::IsAudioMuted() {
1236 return web_contents()->IsAudioMuted();
1239 void WebContents::Print(mate::Arguments* args) {
1240 PrintSettings settings = { false, false };
1241 if (args->Length() == 1 && !args->GetNext(&settings)) {
1246 printing::PrintViewManagerBasic::FromWebContents(web_contents())->
1247 PrintNow(web_contents()->GetMainFrame(),
1249 settings.print_background);
1252 void WebContents::PrintToPDF(const base::DictionaryValue& setting,
1253 const PrintToPDFCallback& callback) {
1254 printing::PrintPreviewMessageHandler::FromWebContents(web_contents())->
1255 PrintToPDF(setting, callback);
1258 void WebContents::AddWorkSpace(mate::Arguments* args,
1259 const base::FilePath& path) {
1261 args->ThrowError("path cannot be empty");
1264 DevToolsAddFileSystem(path);
1267 void WebContents::RemoveWorkSpace(mate::Arguments* args,
1268 const base::FilePath& path) {
1270 args->ThrowError("path cannot be empty");
1273 DevToolsRemoveFileSystem(path);
1276 void WebContents::Undo() {
1277 web_contents()->Undo();
1280 void WebContents::Redo() {
1281 web_contents()->Redo();
1284 void WebContents::Cut() {
1285 web_contents()->Cut();
1288 void WebContents::Copy() {
1289 web_contents()->Copy();
1292 void WebContents::Paste() {
1293 web_contents()->Paste();
1296 void WebContents::PasteAndMatchStyle() {
1297 web_contents()->PasteAndMatchStyle();
1300 void WebContents::Delete() {
1301 web_contents()->Delete();
1304 void WebContents::SelectAll() {
1305 web_contents()->SelectAll();
1308 void WebContents::Unselect() {
1309 web_contents()->Unselect();
1312 void WebContents::Replace(const base::string16& word) {
1313 web_contents()->Replace(word);
1316 void WebContents::ReplaceMisspelling(const base::string16& word) {
1317 web_contents()->ReplaceMisspelling(word);
1320 uint32_t WebContents::FindInPage(mate::Arguments* args) {
1321 uint32_t request_id = GetNextRequestId();
1322 base::string16 search_text;
1323 blink::WebFindOptions options;
1324 if (!args->GetNext(&search_text) || search_text.empty()) {
1325 args->ThrowError("Must provide a non-empty search content");
1329 args->GetNext(&options);
1331 web_contents()->Find(request_id, search_text, options);
1335 void WebContents::StopFindInPage(content::StopFindAction action) {
1336 web_contents()->StopFinding(action);
1339 void WebContents::ShowDefinitionForSelection() {
1340 #if defined(OS_MACOSX)
1341 const auto view = web_contents()->GetRenderWidgetHostView();
1343 view->ShowDefinitionForSelection();
1347 void WebContents::CopyImageAt(int x, int y) {
1348 const auto host = web_contents()->GetMainFrame();
1350 host->CopyImageAt(x, y);
1353 void WebContents::Focus() {
1354 web_contents()->Focus();
1357 #if !defined(OS_MACOSX)
1358 bool WebContents::IsFocused() const {
1359 auto view = web_contents()->GetRenderWidgetHostView();
1360 if (!view) return false;
1362 if (GetType() != BACKGROUND_PAGE) {
1363 auto window = web_contents()->GetNativeView()->GetToplevelWindow();
1364 if (window && !window->IsVisible())
1368 return view->HasFocus();
1372 void WebContents::TabTraverse(bool reverse) {
1373 web_contents()->FocusThroughTabTraversal(reverse);
1376 bool WebContents::SendIPCMessage(bool all_frames,
1377 const base::string16& channel,
1378 const base::ListValue& args) {
1379 return Send(new AtomViewMsg_Message(routing_id(), all_frames, channel, args));
1382 void WebContents::SendInputEvent(v8::Isolate* isolate,
1383 v8::Local<v8::Value> input_event) {
1384 const auto view = web_contents()->GetRenderWidgetHostView();
1387 const auto host = view->GetRenderWidgetHost();
1391 int type = mate::GetWebInputEventType(isolate, input_event);
1392 if (blink::WebInputEvent::isMouseEventType(type)) {
1393 blink::WebMouseEvent mouse_event;
1394 if (mate::ConvertFromV8(isolate, input_event, &mouse_event)) {
1395 host->ForwardMouseEvent(mouse_event);
1398 } else if (blink::WebInputEvent::isKeyboardEventType(type)) {
1399 content::NativeWebKeyboardEvent keyboard_event;
1400 if (mate::ConvertFromV8(isolate, input_event, &keyboard_event)) {
1401 host->ForwardKeyboardEvent(keyboard_event);
1404 } else if (type == blink::WebInputEvent::MouseWheel) {
1405 blink::WebMouseWheelEvent mouse_wheel_event;
1406 if (mate::ConvertFromV8(isolate, input_event, &mouse_wheel_event)) {
1407 host->ForwardWheelEvent(mouse_wheel_event);
1412 isolate->ThrowException(v8::Exception::Error(mate::StringToV8(
1413 isolate, "Invalid event object")));
1416 void WebContents::BeginFrameSubscription(mate::Arguments* args) {
1417 bool only_dirty = false;
1418 FrameSubscriber::FrameCaptureCallback callback;
1420 args->GetNext(&only_dirty);
1421 if (!args->GetNext(&callback)) {
1426 const auto view = web_contents()->GetRenderWidgetHostView();
1428 std::unique_ptr<FrameSubscriber> frame_subscriber(new FrameSubscriber(
1429 isolate(), view, callback, only_dirty));
1430 view->BeginFrameSubscription(std::move(frame_subscriber));
1434 void WebContents::EndFrameSubscription() {
1435 const auto view = web_contents()->GetRenderWidgetHostView();
1437 view->EndFrameSubscription();
1440 void WebContents::StartDrag(const mate::Dictionary& item,
1441 mate::Arguments* args) {
1442 base::FilePath file;
1443 std::vector<base::FilePath> files;
1444 if (!item.Get("files", &files) && item.Get("file", &file)) {
1445 files.push_back(file);
1448 mate::Handle<NativeImage> icon;
1449 if (!item.Get("icon", &icon) && !file.empty()) {
1450 // TODO(zcbenz): Set default icon from file.
1454 if (icon.IsEmpty()) {
1455 args->ThrowError("Must specify 'icon' option");
1459 #if defined(OS_MACOSX)
1460 // NSWindow.dragImage requires a non-empty NSImage
1461 if (icon->image().IsEmpty()) {
1462 args->ThrowError("Must specify non-empty 'icon' option");
1468 if (!files.empty()) {
1469 base::MessageLoop::ScopedNestableTaskAllower allow(
1470 base::MessageLoop::current());
1471 DragFileItems(files, icon->image(), web_contents()->GetNativeView());
1473 args->ThrowError("Must specify either 'file' or 'files' option");
1477 void WebContents::CapturePage(mate::Arguments* args) {
1479 base::Callback<void(const gfx::Image&)> callback;
1481 if (!(args->Length() == 1 && args->GetNext(&callback)) &&
1482 !(args->Length() == 2 && args->GetNext(&rect)
1483 && args->GetNext(&callback))) {
1488 const auto view = web_contents()->GetRenderWidgetHostView();
1489 const auto host = view ? view->GetRenderWidgetHost() : nullptr;
1490 if (!view || !host) {
1491 callback.Run(gfx::Image());
1495 // Capture full page if user doesn't specify a |rect|.
1496 const gfx::Size view_size = rect.IsEmpty() ? view->GetViewBounds().size() :
1499 // By default, the requested bitmap size is the view size in screen
1500 // coordinates. However, if there's more pixel detail available on the
1501 // current system, increase the requested bitmap size to capture it all.
1502 gfx::Size bitmap_size = view_size;
1503 const gfx::NativeView native_view = view->GetNativeView();
1505 display::Screen::GetScreen()->GetDisplayNearestWindow(native_view)
1506 .device_scale_factor();
1508 bitmap_size = gfx::ScaleToCeiledSize(view_size, scale);
1510 host->CopyFromBackingStore(gfx::Rect(rect.origin(), view_size),
1512 base::Bind(&OnCapturePageDone, callback),
1513 kBGRA_8888_SkColorType);
1516 void WebContents::OnCursorChange(const content::WebCursor& cursor) {
1517 content::WebCursor::CursorInfo info;
1518 cursor.GetCursorInfo(&info);
1520 if (cursor.IsCustom()) {
1521 Emit("cursor-changed", CursorTypeToString(info),
1522 gfx::Image::CreateFrom1xBitmap(info.custom_image),
1523 info.image_scale_factor,
1524 gfx::Size(info.custom_image.width(), info.custom_image.height()),
1527 Emit("cursor-changed", CursorTypeToString(info));
1531 void WebContents::SetSize(const SetSizeParams& params) {
1532 if (guest_delegate_)
1533 guest_delegate_->SetSize(params);
1536 bool WebContents::IsGuest() const {
1537 return type_ == WEB_VIEW;
1540 bool WebContents::IsOffScreen() const {
1541 return type_ == OFF_SCREEN;
1544 void WebContents::OnPaint(const gfx::Rect& dirty_rect, const SkBitmap& bitmap) {
1545 mate::Handle<NativeImage> image =
1546 NativeImage::Create(isolate(), gfx::Image::CreateFrom1xBitmap(bitmap));
1547 Emit("paint", dirty_rect, image);
1550 void WebContents::StartPainting() {
1554 auto* osr_rwhv = static_cast<OffScreenRenderWidgetHostView*>(
1555 web_contents()->GetRenderWidgetHostView());
1557 osr_rwhv->SetPainting(true);
1560 void WebContents::StopPainting() {
1564 auto* osr_rwhv = static_cast<OffScreenRenderWidgetHostView*>(
1565 web_contents()->GetRenderWidgetHostView());
1567 osr_rwhv->SetPainting(false);
1570 bool WebContents::IsPainting() const {
1574 const auto* osr_rwhv = static_cast<OffScreenRenderWidgetHostView*>(
1575 web_contents()->GetRenderWidgetHostView());
1576 return osr_rwhv && osr_rwhv->IsPainting();
1579 void WebContents::SetFrameRate(int frame_rate) {
1583 auto* osr_rwhv = static_cast<OffScreenRenderWidgetHostView*>(
1584 web_contents()->GetRenderWidgetHostView());
1586 osr_rwhv->SetFrameRate(frame_rate);
1589 int WebContents::GetFrameRate() const {
1593 const auto* osr_rwhv = static_cast<OffScreenRenderWidgetHostView*>(
1594 web_contents()->GetRenderWidgetHostView());
1595 return osr_rwhv ? osr_rwhv->GetFrameRate() : 0;
1598 void WebContents::Invalidate() {
1599 if (IsOffScreen()) {
1600 auto* osr_rwhv = static_cast<OffScreenRenderWidgetHostView*>(
1601 web_contents()->GetRenderWidgetHostView());
1603 osr_rwhv->Invalidate();
1605 const auto window = owner_window();
1607 window->Invalidate();
1611 void WebContents::SetZoomLevel(double level) {
1612 zoom_controller_->SetZoomLevel(level);
1615 double WebContents::GetZoomLevel() {
1616 return zoom_controller_->GetZoomLevel();
1619 void WebContents::SetZoomFactor(double factor) {
1620 auto level = content::ZoomFactorToZoomLevel(factor);
1621 SetZoomLevel(level);
1624 double WebContents::GetZoomFactor() {
1625 auto level = GetZoomLevel();
1626 return content::ZoomLevelToZoomFactor(level);
1629 void WebContents::OnSetTemporaryZoomLevel(double level,
1630 IPC::Message* reply_msg) {
1631 zoom_controller_->SetTemporaryZoomLevel(level);
1632 double new_level = zoom_controller_->GetZoomLevel();
1633 AtomViewHostMsg_SetTemporaryZoomLevel::WriteReplyParams(reply_msg, new_level);
1637 void WebContents::OnGetZoomLevel(IPC::Message* reply_msg) {
1638 AtomViewHostMsg_GetZoomLevel::WriteReplyParams(reply_msg, GetZoomLevel());
1642 v8::Local<v8::Value> WebContents::GetWebPreferences(v8::Isolate* isolate) {
1643 WebContentsPreferences* web_preferences =
1644 WebContentsPreferences::FromWebContents(web_contents());
1645 return mate::ConvertToV8(isolate, *web_preferences->web_preferences());
1648 v8::Local<v8::Value> WebContents::GetOwnerBrowserWindow() {
1650 return Window::From(isolate(), owner_window());
1652 return v8::Null(isolate());
1655 int32_t WebContents::ID() const {
1656 return weak_map_id();
1659 v8::Local<v8::Value> WebContents::Session(v8::Isolate* isolate) {
1660 return v8::Local<v8::Value>::New(isolate, session_);
1663 content::WebContents* WebContents::HostWebContents() {
1666 return embedder_->web_contents();
1669 void WebContents::SetEmbedder(const WebContents* embedder) {
1671 NativeWindow* owner_window = nullptr;
1672 auto relay = NativeWindowRelay::FromWebContents(embedder->web_contents());
1674 owner_window = relay->window.get();
1677 SetOwnerWindow(owner_window);
1679 content::RenderWidgetHostView* rwhv =
1680 web_contents()->GetRenderWidgetHostView();
1688 v8::Local<v8::Value> WebContents::DevToolsWebContents(v8::Isolate* isolate) {
1689 if (devtools_web_contents_.IsEmpty())
1690 return v8::Null(isolate);
1692 return v8::Local<v8::Value>::New(isolate, devtools_web_contents_);
1695 v8::Local<v8::Value> WebContents::Debugger(v8::Isolate* isolate) {
1696 if (debugger_.IsEmpty()) {
1697 auto handle = atom::api::Debugger::Create(isolate, web_contents());
1698 debugger_.Reset(isolate, handle.ToV8());
1700 return v8::Local<v8::Value>::New(isolate, debugger_);
1704 void WebContents::BuildPrototype(v8::Isolate* isolate,
1705 v8::Local<v8::FunctionTemplate> prototype) {
1706 prototype->SetClassName(mate::StringToV8(isolate, "WebContents"));
1707 mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
1709 .SetMethod("getId", &WebContents::GetID)
1710 .SetMethod("getProcessId", &WebContents::GetProcessID)
1711 .SetMethod("equal", &WebContents::Equal)
1712 .SetMethod("_loadURL", &WebContents::LoadURL)
1713 .SetMethod("downloadURL", &WebContents::DownloadURL)
1714 .SetMethod("_getURL", &WebContents::GetURL)
1715 .SetMethod("getTitle", &WebContents::GetTitle)
1716 .SetMethod("isLoading", &WebContents::IsLoading)
1717 .SetMethod("isLoadingMainFrame", &WebContents::IsLoadingMainFrame)
1718 .SetMethod("isWaitingForResponse", &WebContents::IsWaitingForResponse)
1719 .SetMethod("_stop", &WebContents::Stop)
1720 .SetMethod("_goBack", &WebContents::GoBack)
1721 .SetMethod("_goForward", &WebContents::GoForward)
1722 .SetMethod("_goToOffset", &WebContents::GoToOffset)
1723 .SetMethod("isCrashed", &WebContents::IsCrashed)
1724 .SetMethod("setUserAgent", &WebContents::SetUserAgent)
1725 .SetMethod("getUserAgent", &WebContents::GetUserAgent)
1726 .SetMethod("savePage", &WebContents::SavePage)
1727 .SetMethod("openDevTools", &WebContents::OpenDevTools)
1728 .SetMethod("closeDevTools", &WebContents::CloseDevTools)
1729 .SetMethod("isDevToolsOpened", &WebContents::IsDevToolsOpened)
1730 .SetMethod("isDevToolsFocused", &WebContents::IsDevToolsFocused)
1731 .SetMethod("enableDeviceEmulation",
1732 &WebContents::EnableDeviceEmulation)
1733 .SetMethod("disableDeviceEmulation",
1734 &WebContents::DisableDeviceEmulation)
1735 .SetMethod("toggleDevTools", &WebContents::ToggleDevTools)
1736 .SetMethod("inspectElement", &WebContents::InspectElement)
1737 .SetMethod("setAudioMuted", &WebContents::SetAudioMuted)
1738 .SetMethod("isAudioMuted", &WebContents::IsAudioMuted)
1739 .SetMethod("undo", &WebContents::Undo)
1740 .SetMethod("redo", &WebContents::Redo)
1741 .SetMethod("cut", &WebContents::Cut)
1742 .SetMethod("copy", &WebContents::Copy)
1743 .SetMethod("paste", &WebContents::Paste)
1744 .SetMethod("pasteAndMatchStyle", &WebContents::PasteAndMatchStyle)
1745 .SetMethod("delete", &WebContents::Delete)
1746 .SetMethod("selectAll", &WebContents::SelectAll)
1747 .SetMethod("unselect", &WebContents::Unselect)
1748 .SetMethod("replace", &WebContents::Replace)
1749 .SetMethod("replaceMisspelling", &WebContents::ReplaceMisspelling)
1750 .SetMethod("findInPage", &WebContents::FindInPage)
1751 .SetMethod("stopFindInPage", &WebContents::StopFindInPage)
1752 .SetMethod("focus", &WebContents::Focus)
1753 .SetMethod("isFocused", &WebContents::IsFocused)
1754 .SetMethod("tabTraverse", &WebContents::TabTraverse)
1755 .SetMethod("_send", &WebContents::SendIPCMessage)
1756 .SetMethod("sendInputEvent", &WebContents::SendInputEvent)
1757 .SetMethod("beginFrameSubscription",
1758 &WebContents::BeginFrameSubscription)
1759 .SetMethod("endFrameSubscription", &WebContents::EndFrameSubscription)
1760 .SetMethod("startDrag", &WebContents::StartDrag)
1761 .SetMethod("setSize", &WebContents::SetSize)
1762 .SetMethod("isGuest", &WebContents::IsGuest)
1763 .SetMethod("isOffscreen", &WebContents::IsOffScreen)
1764 .SetMethod("startPainting", &WebContents::StartPainting)
1765 .SetMethod("stopPainting", &WebContents::StopPainting)
1766 .SetMethod("isPainting", &WebContents::IsPainting)
1767 .SetMethod("setFrameRate", &WebContents::SetFrameRate)
1768 .SetMethod("getFrameRate", &WebContents::GetFrameRate)
1769 .SetMethod("invalidate", &WebContents::Invalidate)
1770 .SetMethod("setZoomLevel", &WebContents::SetZoomLevel)
1771 .SetMethod("_getZoomLevel", &WebContents::GetZoomLevel)
1772 .SetMethod("setZoomFactor", &WebContents::SetZoomFactor)
1773 .SetMethod("_getZoomFactor", &WebContents::GetZoomFactor)
1774 .SetMethod("getType", &WebContents::GetType)
1775 .SetMethod("getWebPreferences", &WebContents::GetWebPreferences)
1776 .SetMethod("getOwnerBrowserWindow", &WebContents::GetOwnerBrowserWindow)
1777 .SetMethod("hasServiceWorker", &WebContents::HasServiceWorker)
1778 .SetMethod("unregisterServiceWorker",
1779 &WebContents::UnregisterServiceWorker)
1780 .SetMethod("inspectServiceWorker", &WebContents::InspectServiceWorker)
1781 .SetMethod("print", &WebContents::Print)
1782 .SetMethod("_printToPDF", &WebContents::PrintToPDF)
1783 .SetMethod("addWorkSpace", &WebContents::AddWorkSpace)
1784 .SetMethod("removeWorkSpace", &WebContents::RemoveWorkSpace)
1785 .SetMethod("showDefinitionForSelection",
1786 &WebContents::ShowDefinitionForSelection)
1787 .SetMethod("copyImageAt", &WebContents::CopyImageAt)
1788 .SetMethod("capturePage", &WebContents::CapturePage)
1789 .SetMethod("setEmbedder", &WebContents::SetEmbedder)
1790 .SetMethod("setWebRTCIPHandlingPolicy",
1791 &WebContents::SetWebRTCIPHandlingPolicy)
1792 .SetMethod("getWebRTCIPHandlingPolicy",
1793 &WebContents::GetWebRTCIPHandlingPolicy)
1794 .SetProperty("id", &WebContents::ID)
1795 .SetProperty("session", &WebContents::Session)
1796 .SetProperty("hostWebContents", &WebContents::HostWebContents)
1797 .SetProperty("devToolsWebContents", &WebContents::DevToolsWebContents)
1798 .SetProperty("debugger", &WebContents::Debugger);
1801 AtomBrowserContext* WebContents::GetBrowserContext() const {
1802 return static_cast<AtomBrowserContext*>(web_contents()->GetBrowserContext());
1805 void WebContents::OnRendererMessage(const base::string16& channel,
1806 const base::ListValue& args) {
1807 // webContents.emit(channel, new Event(), args...);
1808 Emit(base::UTF16ToUTF8(channel), args);
1811 void WebContents::OnRendererMessageSync(const base::string16& channel,
1812 const base::ListValue& args,
1813 IPC::Message* message) {
1814 // webContents.emit(channel, new Event(sender, message), args...);
1815 EmitWithSender(base::UTF16ToUTF8(channel), web_contents(), message, args);
1819 mate::Handle<WebContents> WebContents::CreateFrom(
1820 v8::Isolate* isolate, content::WebContents* web_contents) {
1821 // We have an existing WebContents object in JS.
1822 auto existing = TrackableObject::FromWrappedClass(isolate, web_contents);
1824 return mate::CreateHandle(isolate, static_cast<WebContents*>(existing));
1826 // Otherwise create a new WebContents wrapper object.
1827 return mate::CreateHandle(isolate, new WebContents(isolate, web_contents,
1831 mate::Handle<WebContents> WebContents::CreateFrom(
1832 v8::Isolate* isolate, content::WebContents* web_contents, Type type) {
1833 // Otherwise create a new WebContents wrapper object.
1834 return mate::CreateHandle(isolate, new WebContents(isolate, web_contents,
1839 mate::Handle<WebContents> WebContents::Create(
1840 v8::Isolate* isolate, const mate::Dictionary& options) {
1841 return mate::CreateHandle(isolate, new WebContents(isolate, options));
1850 using atom::api::WebContents;
1852 void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused,
1853 v8::Local<v8::Context> context, void* priv) {
1854 v8::Isolate* isolate = context->GetIsolate();
1855 mate::Dictionary dict(isolate, exports);
1856 dict.Set("WebContents", WebContents::GetConstructor(isolate)->GetFunction());
1857 dict.SetMethod("create", &WebContents::Create);
1858 dict.SetMethod("fromId", &mate::TrackableObject<WebContents>::FromWeakMapID);
1859 dict.SetMethod("getAllWebContents",
1860 &mate::TrackableObject<WebContents>::GetAll);
1865 NODE_MODULE_CONTEXT_AWARE_BUILTIN(atom_browser_web_contents, Initialize)