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::REMOTE: type = "remote"; break;
192 case Type::WEB_VIEW: type = "webview"; break;
193 case Type::OFF_SCREEN: type = "offscreen"; break;
196 return mate::ConvertToV8(isolate, type);
199 static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val,
200 atom::api::WebContents::Type* out) {
201 using Type = atom::api::WebContents::Type;
203 if (!ConvertFromV8(isolate, val, &type))
205 if (type == "webview") {
206 *out = Type::WEB_VIEW;
207 } else if (type == "backgroundPage") {
208 *out = Type::BACKGROUND_PAGE;
209 } else if (type == "offscreen") {
210 *out = Type::OFF_SCREEN;
227 content::ServiceWorkerContext* GetServiceWorkerContext(
228 const content::WebContents* web_contents) {
229 auto context = web_contents->GetBrowserContext();
230 auto site_instance = web_contents->GetSiteInstance();
231 if (!context || !site_instance)
234 auto storage_partition =
235 content::BrowserContext::GetStoragePartition(context, site_instance);
236 if (!storage_partition)
239 return storage_partition->GetServiceWorkerContext();
242 // Called when CapturePage is done.
243 void OnCapturePageDone(base::Callback<void(const gfx::Image&)> callback,
244 const SkBitmap& bitmap,
245 content::ReadbackResponse response) {
246 callback.Run(gfx::Image::CreateFrom1xBitmap(bitmap));
249 // Set the background color of RenderWidgetHostView.
250 void SetBackgroundColor(content::WebContents* web_contents) {
251 const auto view = web_contents->GetRenderWidgetHostView();
253 WebContentsPreferences* web_preferences =
254 WebContentsPreferences::FromWebContents(web_contents);
255 std::string color_name;
256 if (web_preferences->web_preferences()->GetString(options::kBackgroundColor,
258 view->SetBackgroundColor(ParseHexColor(color_name));
260 view->SetBackgroundColor(SK_ColorTRANSPARENT);
267 WebContents::WebContents(v8::Isolate* isolate,
268 content::WebContents* web_contents,
270 : content::WebContentsObserver(web_contents),
272 zoom_controller_(nullptr),
275 background_throttling_(true),
276 enable_devtools_(true) {
277 if (type == REMOTE) {
278 web_contents->SetUserAgentOverride(GetBrowserContext()->GetUserAgent());
280 AttachAsUserData(web_contents);
282 const mate::Dictionary options = mate::Dictionary::CreateEmpty(isolate);
283 auto session = Session::CreateFrom(isolate, GetBrowserContext());
284 session_.Reset(isolate, session.ToV8());
285 InitWithSessionAndOptions(isolate, web_contents, session, options);
289 WebContents::WebContents(v8::Isolate* isolate, const mate::Dictionary& options)
290 : embedder_(nullptr),
291 zoom_controller_(nullptr),
292 type_(BROWSER_WINDOW),
294 background_throttling_(true),
295 enable_devtools_(true) {
297 options.Get("backgroundThrottling", &background_throttling_);
299 // FIXME(zcbenz): We should read "type" parameter for better design, but
300 // on Windows we have encountered a compiler bug that if we read "type"
301 // from |options| and then set |type_|, a memory corruption will happen
302 // and Electron will soon crash.
303 // Remvoe this after we upgraded to use VS 2015 Update 3.
305 if (options.Get("isGuest", &b) && b)
307 else if (options.Get("isBackgroundPage", &b) && b)
308 type_ = BACKGROUND_PAGE;
309 else if (options.Get("offscreen", &b) && b)
312 // Whether to enable DevTools.
313 options.Get("devTools", &enable_devtools_);
315 // Obtain the session.
316 std::string partition;
317 mate::Handle<api::Session> session;
318 if (options.Get("session", &session)) {
319 } else if (options.Get("partition", &partition)) {
320 session = Session::FromPartition(isolate, partition);
322 // Use the default session if not specified.
323 session = Session::FromPartition(isolate, "");
325 session_.Reset(isolate, session.ToV8());
327 content::WebContents* web_contents;
329 scoped_refptr<content::SiteInstance> site_instance =
330 content::SiteInstance::CreateForURL(
331 session->browser_context(), GURL("chrome-guest://fake-host"));
332 content::WebContents::CreateParams params(
333 session->browser_context(), site_instance);
334 guest_delegate_.reset(new WebViewGuestDelegate);
335 params.guest_delegate = guest_delegate_.get();
336 web_contents = content::WebContents::Create(params);
337 } else if (IsOffScreen()) {
338 bool transparent = false;
339 options.Get("transparent", &transparent);
341 content::WebContents::CreateParams params(session->browser_context());
342 auto* view = new OffScreenWebContentsView(
343 transparent, base::Bind(&WebContents::OnPaint, base::Unretained(this)));
345 params.delegate_view = view;
347 web_contents = content::WebContents::Create(params);
348 view->SetWebContents(web_contents);
350 content::WebContents::CreateParams params(session->browser_context());
351 web_contents = content::WebContents::Create(params);
354 InitWithSessionAndOptions(isolate, web_contents, session, options);
357 void WebContents::InitWithSessionAndOptions(v8::Isolate* isolate,
358 content::WebContents *web_contents,
359 mate::Handle<api::Session> session,
360 const mate::Dictionary& options) {
361 content::WebContentsObserver::Observe(web_contents);
362 InitWithWebContents(web_contents, session->browser_context());
364 managed_web_contents()->GetView()->SetDelegate(this);
366 // Save the preferences in C++.
367 new WebContentsPreferences(web_contents, options);
369 // Initialize permission helper.
370 WebContentsPermissionHelper::CreateForWebContents(web_contents);
371 // Initialize security state client.
372 SecurityStateTabHelper::CreateForWebContents(web_contents);
373 // Initialize zoom controller.
374 WebContentsZoomController::CreateForWebContents(web_contents);
375 zoom_controller_ = WebContentsZoomController::FromWebContents(web_contents);
377 if (options.Get(options::kZoomFactor, &zoom_factor))
378 zoom_controller_->SetDefaultZoomFactor(zoom_factor);
380 web_contents->SetUserAgentOverride(GetBrowserContext()->GetUserAgent());
383 guest_delegate_->Initialize(this);
385 NativeWindow* owner_window = nullptr;
386 if (options.Get("embedder", &embedder_) && embedder_) {
387 // New WebContents's owner_window is the embedder's owner_window.
389 NativeWindowRelay::FromWebContents(embedder_->web_contents());
391 owner_window = relay->window.get();
394 SetOwnerWindow(owner_window);
397 const content::NavigationController* controller =
398 &web_contents->GetController();
399 registrar_.Add(this, content::NOTIFICATION_NAV_ENTRY_PENDING,
400 content::Source<content::NavigationController>(controller));
403 AttachAsUserData(web_contents);
406 WebContents::~WebContents() {
407 // The destroy() is called.
408 if (managed_web_contents()) {
409 // For webview we need to tell content module to do some cleanup work before
411 if (type_ == WEB_VIEW)
412 guest_delegate_->Destroy();
414 // The WebContentsDestroyed will not be called automatically because we
415 // unsubscribe from webContents before destroying it. So we have to manually
416 // call it here to make sure "destroyed" event is emitted.
417 RenderViewDeleted(web_contents()->GetRenderViewHost());
418 WebContentsDestroyed();
422 bool WebContents::DidAddMessageToConsole(content::WebContents* source,
424 const base::string16& message,
426 const base::string16& source_id) {
427 if (type_ == BROWSER_WINDOW || type_ == OFF_SCREEN) {
430 Emit("console-message", level, message, line_no, source_id);
435 void WebContents::OnCreateWindow(
436 const GURL& target_url,
437 const std::string& frame_name,
438 WindowOpenDisposition disposition,
439 const std::vector<std::string>& features,
440 const scoped_refptr<content::ResourceRequestBodyImpl>& body) {
441 if (type_ == BROWSER_WINDOW || type_ == OFF_SCREEN)
442 Emit("-new-window", target_url, frame_name, disposition, features, body);
444 Emit("new-window", target_url, frame_name, disposition, features);
447 void WebContents::WebContentsCreated(content::WebContents* source_contents,
448 int opener_render_process_id,
449 int opener_render_frame_id,
450 const std::string& frame_name,
451 const GURL& target_url,
452 content::WebContents* new_contents) {
453 v8::Locker locker(isolate());
454 v8::HandleScope handle_scope(isolate());
455 auto api_web_contents = CreateFrom(isolate(), new_contents, BROWSER_WINDOW);
456 Emit("-web-contents-created", api_web_contents, target_url, frame_name);
459 void WebContents::AddNewContents(content::WebContents* source,
460 content::WebContents* new_contents,
461 WindowOpenDisposition disposition,
462 const gfx::Rect& initial_rect,
465 v8::Locker locker(isolate());
466 v8::HandleScope handle_scope(isolate());
467 auto api_web_contents = CreateFrom(isolate(), new_contents);
468 if (Emit("-add-new-contents", api_web_contents, disposition, user_gesture,
469 initial_rect.x(), initial_rect.y(), initial_rect.width(),
470 initial_rect.height())) {
471 api_web_contents->DestroyWebContents();
475 content::WebContents* WebContents::OpenURLFromTab(
476 content::WebContents* source,
477 const content::OpenURLParams& params) {
478 if (params.disposition != WindowOpenDisposition::CURRENT_TAB) {
479 if (type_ == BROWSER_WINDOW || type_ == OFF_SCREEN)
480 Emit("-new-window", params.url, "", params.disposition);
482 Emit("new-window", params.url, "", params.disposition);
486 // Give user a chance to cancel navigation.
487 if (Emit("will-navigate", params.url))
490 // Don't load the URL if the web contents was marked as destroyed from a
491 // will-navigate event listener
495 return CommonWebContentsDelegate::OpenURLFromTab(source, params);
498 void WebContents::BeforeUnloadFired(content::WebContents* tab,
500 bool* proceed_to_fire_unload) {
501 if (type_ == BROWSER_WINDOW || type_ == OFF_SCREEN)
502 *proceed_to_fire_unload = proceed;
504 *proceed_to_fire_unload = true;
507 void WebContents::MoveContents(content::WebContents* source,
508 const gfx::Rect& pos) {
512 void WebContents::CloseContents(content::WebContents* source) {
515 if ((type_ == BROWSER_WINDOW || type_ == OFF_SCREEN) && owner_window())
516 owner_window()->CloseContents(source);
519 void WebContents::ActivateContents(content::WebContents* source) {
523 void WebContents::UpdateTargetURL(content::WebContents* source,
525 Emit("update-target-url", url);
528 bool WebContents::IsPopupOrPanel(const content::WebContents* source) const {
529 return type_ == BROWSER_WINDOW;
532 void WebContents::HandleKeyboardEvent(
533 content::WebContents* source,
534 const content::NativeWebKeyboardEvent& event) {
535 if (type_ == WEB_VIEW && embedder_) {
536 // Send the unhandled keyboard events back to the embedder.
537 embedder_->HandleKeyboardEvent(source, event);
539 // Go to the default keyboard handling.
540 CommonWebContentsDelegate::HandleKeyboardEvent(source, event);
544 bool WebContents::PreHandleKeyboardEvent(
545 content::WebContents* source,
546 const content::NativeWebKeyboardEvent& event,
547 bool* is_keyboard_shortcut) {
548 if (event.type == blink::WebInputEvent::Type::RawKeyDown
549 || event.type == blink::WebInputEvent::Type::KeyUp)
550 return Emit("before-input-event", event);
555 void WebContents::EnterFullscreenModeForTab(content::WebContents* source,
556 const GURL& origin) {
557 auto permission_helper =
558 WebContentsPermissionHelper::FromWebContents(source);
559 auto callback = base::Bind(&WebContents::OnEnterFullscreenModeForTab,
560 base::Unretained(this), source, origin);
561 permission_helper->RequestFullscreenPermission(callback);
564 void WebContents::OnEnterFullscreenModeForTab(content::WebContents* source,
569 CommonWebContentsDelegate::EnterFullscreenModeForTab(source, origin);
570 Emit("enter-html-full-screen");
573 void WebContents::ExitFullscreenModeForTab(content::WebContents* source) {
574 CommonWebContentsDelegate::ExitFullscreenModeForTab(source);
575 Emit("leave-html-full-screen");
578 void WebContents::RendererUnresponsive(
579 content::WebContents* source,
580 const content::WebContentsUnresponsiveState& unresponsive_state) {
581 Emit("unresponsive");
582 if ((type_ == BROWSER_WINDOW || type_ == OFF_SCREEN) && owner_window())
583 owner_window()->RendererUnresponsive(source);
586 void WebContents::RendererResponsive(content::WebContents* source) {
588 if ((type_ == BROWSER_WINDOW || type_ == OFF_SCREEN) && owner_window())
589 owner_window()->RendererResponsive(source);
592 bool WebContents::HandleContextMenu(const content::ContextMenuParams& params) {
593 if (params.custom_context.is_pepper_menu) {
594 Emit("pepper-context-menu", std::make_pair(params, web_contents()));
595 web_contents()->NotifyContextMenuClosed(params.custom_context);
597 Emit("context-menu", std::make_pair(params, web_contents()));
603 bool WebContents::OnGoToEntryOffset(int offset) {
608 void WebContents::FindReply(content::WebContents* web_contents,
610 int number_of_matches,
611 const gfx::Rect& selection_rect,
612 int active_match_ordinal,
617 v8::Locker locker(isolate());
618 v8::HandleScope handle_scope(isolate());
619 mate::Dictionary result = mate::Dictionary::CreateEmpty(isolate());
620 result.Set("requestId", request_id);
621 result.Set("matches", number_of_matches);
622 result.Set("selectionArea", selection_rect);
623 result.Set("activeMatchOrdinal", active_match_ordinal);
624 result.Set("finalUpdate", final_update); // Deprecate after 2.0
625 Emit("found-in-page", result);
628 bool WebContents::CheckMediaAccessPermission(
629 content::WebContents* web_contents,
630 const GURL& security_origin,
631 content::MediaStreamType type) {
635 void WebContents::RequestMediaAccessPermission(
636 content::WebContents* web_contents,
637 const content::MediaStreamRequest& request,
638 const content::MediaResponseCallback& callback) {
639 auto permission_helper =
640 WebContentsPermissionHelper::FromWebContents(web_contents);
641 permission_helper->RequestMediaAccessPermission(request, callback);
644 void WebContents::RequestToLockMouse(
645 content::WebContents* web_contents,
647 bool last_unlocked_by_target) {
648 auto permission_helper =
649 WebContentsPermissionHelper::FromWebContents(web_contents);
650 permission_helper->RequestPointerLockPermission(user_gesture);
653 std::unique_ptr<content::BluetoothChooser> WebContents::RunBluetoothChooser(
654 content::RenderFrameHost* frame,
655 const content::BluetoothChooser::EventHandler& event_handler) {
656 std::unique_ptr<BluetoothChooser> bluetooth_chooser(
657 new BluetoothChooser(this, event_handler));
658 return std::move(bluetooth_chooser);
661 void WebContents::BeforeUnloadFired(const base::TimeTicks& proceed_time) {
662 // Do nothing, we override this method just to avoid compilation error since
663 // there are two virtual functions named BeforeUnloadFired.
666 void WebContents::RenderViewCreated(content::RenderViewHost* render_view_host) {
667 const auto impl = content::RenderWidgetHostImpl::FromID(
668 render_view_host->GetProcess()->GetID(),
669 render_view_host->GetRoutingID());
671 impl->disable_hidden_ = !background_throttling_;
674 void WebContents::RenderViewDeleted(content::RenderViewHost* render_view_host) {
675 Emit("render-view-deleted", render_view_host->GetProcess()->GetID());
678 void WebContents::RenderProcessGone(base::TerminationStatus status) {
679 Emit("crashed", status == base::TERMINATION_STATUS_PROCESS_WAS_KILLED);
682 void WebContents::PluginCrashed(const base::FilePath& plugin_path,
683 base::ProcessId plugin_pid) {
684 content::WebPluginInfo info;
685 auto plugin_service = content::PluginService::GetInstance();
686 plugin_service->GetPluginInfoByPath(plugin_path, &info);
687 Emit("plugin-crashed", info.name, info.version);
690 void WebContents::MediaStartedPlaying(const MediaPlayerInfo& video_type,
691 const MediaPlayerId& id) {
692 Emit("media-started-playing");
695 void WebContents::MediaStoppedPlaying(const MediaPlayerInfo& video_type,
696 const MediaPlayerId& id) {
697 Emit("media-paused");
700 void WebContents::DidChangeThemeColor(SkColor theme_color) {
701 Emit("did-change-theme-color", atom::ToRGBHex(theme_color));
704 void WebContents::DocumentLoadedInFrame(
705 content::RenderFrameHost* render_frame_host) {
706 if (!render_frame_host->GetParent())
710 void WebContents::DidFinishLoad(content::RenderFrameHost* render_frame_host,
711 const GURL& validated_url) {
712 bool is_main_frame = !render_frame_host->GetParent();
713 Emit("did-frame-finish-load", is_main_frame);
716 Emit("did-finish-load");
719 void WebContents::DidFailLoad(content::RenderFrameHost* render_frame_host,
722 const base::string16& error_description,
723 bool was_ignored_by_handler) {
724 bool is_main_frame = !render_frame_host->GetParent();
725 Emit("did-fail-load", error_code, error_description, url, is_main_frame);
728 void WebContents::DidStartLoading() {
729 Emit("did-start-loading");
732 void WebContents::DidStopLoading() {
733 Emit("did-stop-loading");
736 void WebContents::DidGetResourceResponseStart(
737 const content::ResourceRequestDetails& details) {
738 Emit("did-get-response-details",
739 details.socket_address.IsEmpty(),
741 details.original_url,
742 details.http_response_code,
745 details.headers.get(),
746 ResourceTypeToString(details.resource_type));
749 void WebContents::DidGetRedirectForResourceRequest(
750 const content::ResourceRedirectDetails& details) {
751 Emit("did-get-redirect-request",
754 (details.resource_type == content::RESOURCE_TYPE_MAIN_FRAME),
755 details.http_response_code,
758 details.headers.get());
761 void WebContents::DidStartNavigation(
762 content::NavigationHandle* navigation_handle) {
763 if (!navigation_handle->IsInMainFrame() || navigation_handle->IsSamePage())
766 if (deferred_load_url_.id) {
767 auto web_contents = navigation_handle->GetWebContents();
768 auto& controller = web_contents->GetController();
769 int id = controller.GetPendingEntry()->GetUniqueID();
770 if (id == deferred_load_url_.id) {
771 if (!deferred_load_url_.params.url.is_empty()) {
772 auto params = deferred_load_url_.params;
773 deferred_load_url_.id = 0;
774 deferred_load_url_.params =
775 content::NavigationController::LoadURLParams(GURL());
776 controller.LoadURLWithParams(params);
777 SetBackgroundColor(web_contents);
779 deferred_load_url_.id = 0;
785 void WebContents::DidFinishNavigation(
786 content::NavigationHandle* navigation_handle) {
787 bool is_main_frame = navigation_handle->IsInMainFrame();
788 if (navigation_handle->HasCommitted() && !navigation_handle->IsErrorPage()) {
789 auto url = navigation_handle->GetURL();
790 bool is_in_page = navigation_handle->IsSamePage();
791 if (is_main_frame && !is_in_page) {
792 Emit("did-navigate", url);
793 } else if (is_in_page) {
794 Emit("did-navigate-in-page", url, is_main_frame);
797 auto url = navigation_handle->GetURL();
798 int code = navigation_handle->GetNetErrorCode();
799 auto description = net::ErrorToShortString(code);
800 Emit("did-fail-provisional-load", code, description, url, is_main_frame);
802 // Do not emit "did-fail-load" for canceled requests.
803 if (code != net::ERR_ABORTED)
804 Emit("did-fail-load", code, description, url, is_main_frame);
808 void WebContents::TitleWasSet(content::NavigationEntry* entry,
811 Emit("-page-title-updated", entry->GetTitle(), explicit_set);
813 Emit("-page-title-updated", "", explicit_set);
816 void WebContents::DidUpdateFaviconURL(
817 const std::vector<content::FaviconURL>& urls) {
818 std::set<GURL> unique_urls;
819 for (const auto& iter : urls) {
820 if (iter.icon_type != content::FaviconURL::FAVICON)
822 const GURL& url = iter.icon_url;
824 unique_urls.insert(url);
826 Emit("page-favicon-updated", unique_urls);
829 void WebContents::Observe(int type,
830 const content::NotificationSource& source,
831 const content::NotificationDetails& details) {
833 case content::NOTIFICATION_NAV_ENTRY_PENDING: {
834 content::NavigationEntry* entry =
835 content::Details<content::NavigationEntry>(details).ptr();
836 content::NavigationEntryImpl* entry_impl =
837 static_cast<content::NavigationEntryImpl*>(entry);
838 // In NavigatorImpl::DidStartMainFrameNavigation when there is no
839 // browser side pending entry available it creates a new one based
840 // on existing pending entry, hence we track the unique id here
841 // instead in WebContents::LoadURL with controller.GetPendingEntry()
842 // TODO(deepak1556): Remove once we have
843 // https://codereview.chromium.org/2661743002.
844 if (entry_impl->frame_tree_node_id() == -1) {
845 deferred_load_url_.id = entry->GetUniqueID();
855 void WebContents::DevToolsReloadPage() {
856 Emit("devtools-reload-page");
859 void WebContents::DevToolsFocused() {
860 Emit("devtools-focused");
863 void WebContents::DevToolsOpened() {
864 v8::Locker locker(isolate());
865 v8::HandleScope handle_scope(isolate());
866 auto handle = WebContents::CreateFrom(
867 isolate(), managed_web_contents()->GetDevToolsWebContents());
868 devtools_web_contents_.Reset(isolate(), handle.ToV8());
870 // Set inspected tabID.
871 base::FundamentalValue tab_id(ID());
872 managed_web_contents()->CallClientFunction(
873 "DevToolsAPI.setInspectedTabId", &tab_id, nullptr, nullptr);
875 // Inherit owner window in devtools.
877 handle->SetOwnerWindow(managed_web_contents()->GetDevToolsWebContents(),
880 Emit("devtools-opened");
883 void WebContents::DevToolsClosed() {
884 v8::Locker locker(isolate());
885 v8::HandleScope handle_scope(isolate());
886 devtools_web_contents_.Reset();
888 Emit("devtools-closed");
891 bool WebContents::OnMessageReceived(const IPC::Message& message) {
893 IPC_BEGIN_MESSAGE_MAP(WebContents, message)
894 IPC_MESSAGE_HANDLER(AtomViewHostMsg_Message, OnRendererMessage)
895 IPC_MESSAGE_HANDLER_DELAY_REPLY(AtomViewHostMsg_Message_Sync,
896 OnRendererMessageSync)
897 IPC_MESSAGE_HANDLER_DELAY_REPLY(AtomViewHostMsg_SetTemporaryZoomLevel,
898 OnSetTemporaryZoomLevel)
899 IPC_MESSAGE_HANDLER_DELAY_REPLY(AtomViewHostMsg_GetZoomLevel,
901 IPC_MESSAGE_HANDLER_CODE(ViewHostMsg_SetCursor, OnCursorChange,
903 IPC_MESSAGE_UNHANDLED(handled = false)
904 IPC_END_MESSAGE_MAP()
909 // There are three ways of destroying a webContents:
910 // 1. call webContents.destroy();
911 // 2. garbage collection;
912 // 3. user closes the window of webContents;
913 // For webview only #1 will happen, for BrowserWindow both #1 and #3 may
914 // happen. The #2 should never happen for webContents, because webview is
915 // managed by GuestViewManager, and BrowserWindow's webContents is managed
917 // For #1, the destructor will do the cleanup work and we only need to make
918 // sure "destroyed" event is emitted. For #3, the content::WebContents will
919 // be destroyed on close, and WebContentsDestroyed would be called for it, so
920 // we need to make sure the api::WebContents is also deleted.
921 void WebContents::WebContentsDestroyed() {
922 // This event is only for internal use, which is emitted when WebContents is
924 Emit("will-destroy");
926 // Cleanup relationships with other parts.
929 // We can not call Destroy here because we need to call Emit first, but we
930 // also do not want any method to be used, so just mark as destroyed here.
935 // Destroy the native class in next tick.
936 base::ThreadTaskRunnerHandle::Get()->PostTask(
937 FROM_HERE, GetDestroyClosure());
940 void WebContents::NavigationEntryCommitted(
941 const content::LoadCommittedDetails& details) {
942 Emit("navigation-entry-commited", details.entry->GetURL(),
943 details.is_in_page, details.did_replace_entry);
946 int64_t WebContents::GetID() const {
947 int64_t process_id = web_contents()->GetRenderProcessHost()->GetID();
948 int64_t routing_id = web_contents()->GetRoutingID();
949 int64_t rv = (process_id << 32) + routing_id;
953 int WebContents::GetProcessID() const {
954 return web_contents()->GetRenderProcessHost()->GetID();
957 WebContents::Type WebContents::GetType() const {
961 bool WebContents::Equal(const WebContents* web_contents) const {
962 return GetID() == web_contents->GetID();
965 void WebContents::LoadURL(const GURL& url, const mate::Dictionary& options) {
966 if (!url.is_valid() || url.spec().size() > url::kMaxURLChars) {
967 Emit("did-fail-load",
968 static_cast<int>(net::ERR_INVALID_URL),
969 net::ErrorToShortString(net::ERR_INVALID_URL),
970 url.possibly_invalid_spec(),
975 content::NavigationController::LoadURLParams params(url);
978 if (options.Get("httpReferrer", &http_referrer))
979 params.referrer = content::Referrer(http_referrer.GetAsReferrer(),
980 blink::WebReferrerPolicyDefault);
982 std::string user_agent;
983 if (options.Get("userAgent", &user_agent))
984 web_contents()->SetUserAgentOverride(user_agent);
986 std::string extra_headers;
987 if (options.Get("extraHeaders", &extra_headers))
988 params.extra_headers = extra_headers;
990 scoped_refptr<content::ResourceRequestBodyImpl> body;
991 if (options.Get("postData", &body)) {
992 params.post_data = body;
993 params.load_type = content::NavigationController::LOAD_TYPE_HTTP_POST;
996 GURL base_url_for_data_url;
997 if (options.Get("baseURLForDataURL", &base_url_for_data_url)) {
998 params.base_url_for_data_url = base_url_for_data_url;
999 params.load_type = content::NavigationController::LOAD_TYPE_DATA;
1002 params.transition_type = ui::PAGE_TRANSITION_TYPED;
1003 params.should_clear_history_list = true;
1004 params.override_user_agent = content::NavigationController::UA_OVERRIDE_TRUE;
1006 if (deferred_load_url_.id) {
1007 deferred_load_url_.params = params;
1011 web_contents()->GetController().LoadURLWithParams(params);
1012 // We have to call it right after LoadURL because the RenderViewHost is only
1013 // created after loading a page.
1014 SetBackgroundColor(web_contents());
1017 void WebContents::DownloadURL(const GURL& url) {
1018 auto browser_context = web_contents()->GetBrowserContext();
1019 auto download_manager =
1020 content::BrowserContext::GetDownloadManager(browser_context);
1022 download_manager->DownloadUrl(
1023 content::DownloadUrlParameters::CreateForWebContentsMainFrame(
1024 web_contents(), url));
1027 GURL WebContents::GetURL() const {
1028 return web_contents()->GetURL();
1031 base::string16 WebContents::GetTitle() const {
1032 return web_contents()->GetTitle();
1035 bool WebContents::IsLoading() const {
1036 return web_contents()->IsLoading();
1039 bool WebContents::IsLoadingMainFrame() const {
1040 // Comparing site instances works because Electron always creates a new site
1041 // instance when navigating, regardless of origin. See AtomBrowserClient.
1042 return (web_contents()->GetLastCommittedURL().is_empty() ||
1043 web_contents()->GetSiteInstance() !=
1044 web_contents()->GetPendingSiteInstance()) && IsLoading();
1047 bool WebContents::IsWaitingForResponse() const {
1048 return web_contents()->IsWaitingForResponse();
1051 void WebContents::Stop() {
1052 web_contents()->Stop();
1055 void WebContents::GoBack() {
1056 atom::AtomBrowserClient::SuppressRendererProcessRestartForOnce();
1057 web_contents()->GetController().GoBack();
1060 void WebContents::GoForward() {
1061 atom::AtomBrowserClient::SuppressRendererProcessRestartForOnce();
1062 web_contents()->GetController().GoForward();
1065 void WebContents::GoToOffset(int offset) {
1066 atom::AtomBrowserClient::SuppressRendererProcessRestartForOnce();
1067 web_contents()->GetController().GoToOffset(offset);
1070 const std::string WebContents::GetWebRTCIPHandlingPolicy() const {
1071 return web_contents()->
1072 GetMutableRendererPrefs()->webrtc_ip_handling_policy;
1075 void WebContents::SetWebRTCIPHandlingPolicy(
1076 const std::string& webrtc_ip_handling_policy) {
1077 if (GetWebRTCIPHandlingPolicy() == webrtc_ip_handling_policy)
1079 web_contents()->GetMutableRendererPrefs()->webrtc_ip_handling_policy =
1080 webrtc_ip_handling_policy;
1082 content::RenderViewHost* host = web_contents()->GetRenderViewHost();
1084 host->SyncRendererPrefs();
1087 bool WebContents::IsCrashed() const {
1088 return web_contents()->IsCrashed();
1091 void WebContents::SetUserAgent(const std::string& user_agent,
1092 mate::Arguments* args) {
1093 web_contents()->SetUserAgentOverride(user_agent);
1096 std::string WebContents::GetUserAgent() {
1097 return web_contents()->GetUserAgentOverride();
1100 bool WebContents::SavePage(const base::FilePath& full_file_path,
1101 const content::SavePageType& save_type,
1102 const SavePageHandler::SavePageCallback& callback) {
1103 auto handler = new SavePageHandler(web_contents(), callback);
1104 return handler->Handle(full_file_path, save_type);
1107 void WebContents::OpenDevTools(mate::Arguments* args) {
1108 if (type_ == REMOTE)
1111 if (!enable_devtools_)
1115 if (type_ == WEB_VIEW || !owner_window()) {
1117 } else if (args && args->Length() == 1) {
1118 bool detach = false;
1119 mate::Dictionary options;
1120 if (args->GetNext(&options)) {
1121 options.Get("mode", &state);
1123 // TODO(kevinsawicki) Remove in 2.0
1124 options.Get("detach", &detach);
1125 if (state.empty() && detach)
1129 managed_web_contents()->SetDockState(state);
1130 managed_web_contents()->ShowDevTools();
1133 void WebContents::CloseDevTools() {
1134 if (type_ == REMOTE)
1137 managed_web_contents()->CloseDevTools();
1140 bool WebContents::IsDevToolsOpened() {
1141 if (type_ == REMOTE)
1144 return managed_web_contents()->IsDevToolsViewShowing();
1147 bool WebContents::IsDevToolsFocused() {
1148 if (type_ == REMOTE)
1151 return managed_web_contents()->GetView()->IsDevToolsViewFocused();
1154 void WebContents::EnableDeviceEmulation(
1155 const blink::WebDeviceEmulationParams& params) {
1156 if (type_ == REMOTE)
1159 Send(new ViewMsg_EnableDeviceEmulation(routing_id(), params));
1162 void WebContents::DisableDeviceEmulation() {
1163 if (type_ == REMOTE)
1166 Send(new ViewMsg_DisableDeviceEmulation(routing_id()));
1169 void WebContents::ToggleDevTools() {
1170 if (IsDevToolsOpened())
1173 OpenDevTools(nullptr);
1176 void WebContents::InspectElement(int x, int y) {
1177 if (type_ == REMOTE)
1180 if (!enable_devtools_)
1183 if (!managed_web_contents()->GetDevToolsWebContents())
1184 OpenDevTools(nullptr);
1185 managed_web_contents()->InspectElement(x, y);
1188 void WebContents::InspectServiceWorker() {
1189 if (type_ == REMOTE)
1192 if (!enable_devtools_)
1195 for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) {
1196 if (agent_host->GetType() ==
1197 content::DevToolsAgentHost::kTypeServiceWorker) {
1198 OpenDevTools(nullptr);
1199 managed_web_contents()->AttachTo(agent_host);
1205 void WebContents::HasServiceWorker(
1206 const base::Callback<void(bool)>& callback) {
1207 auto context = GetServiceWorkerContext(web_contents());
1211 context->CheckHasServiceWorker(web_contents()->GetLastCommittedURL(),
1216 void WebContents::UnregisterServiceWorker(
1217 const base::Callback<void(bool)>& callback) {
1218 auto context = GetServiceWorkerContext(web_contents());
1222 context->UnregisterServiceWorker(web_contents()->GetLastCommittedURL(),
1226 void WebContents::SetAudioMuted(bool muted) {
1227 web_contents()->SetAudioMuted(muted);
1230 bool WebContents::IsAudioMuted() {
1231 return web_contents()->IsAudioMuted();
1234 void WebContents::Print(mate::Arguments* args) {
1235 PrintSettings settings = { false, false };
1236 if (args->Length() == 1 && !args->GetNext(&settings)) {
1241 printing::PrintViewManagerBasic::FromWebContents(web_contents())->
1242 PrintNow(web_contents()->GetMainFrame(),
1244 settings.print_background);
1247 void WebContents::PrintToPDF(const base::DictionaryValue& setting,
1248 const PrintToPDFCallback& callback) {
1249 printing::PrintPreviewMessageHandler::FromWebContents(web_contents())->
1250 PrintToPDF(setting, callback);
1253 void WebContents::AddWorkSpace(mate::Arguments* args,
1254 const base::FilePath& path) {
1256 args->ThrowError("path cannot be empty");
1259 DevToolsAddFileSystem(path);
1262 void WebContents::RemoveWorkSpace(mate::Arguments* args,
1263 const base::FilePath& path) {
1265 args->ThrowError("path cannot be empty");
1268 DevToolsRemoveFileSystem(path);
1271 void WebContents::Undo() {
1272 web_contents()->Undo();
1275 void WebContents::Redo() {
1276 web_contents()->Redo();
1279 void WebContents::Cut() {
1280 web_contents()->Cut();
1283 void WebContents::Copy() {
1284 web_contents()->Copy();
1287 void WebContents::Paste() {
1288 web_contents()->Paste();
1291 void WebContents::PasteAndMatchStyle() {
1292 web_contents()->PasteAndMatchStyle();
1295 void WebContents::Delete() {
1296 web_contents()->Delete();
1299 void WebContents::SelectAll() {
1300 web_contents()->SelectAll();
1303 void WebContents::Unselect() {
1304 web_contents()->Unselect();
1307 void WebContents::Replace(const base::string16& word) {
1308 web_contents()->Replace(word);
1311 void WebContents::ReplaceMisspelling(const base::string16& word) {
1312 web_contents()->ReplaceMisspelling(word);
1315 uint32_t WebContents::FindInPage(mate::Arguments* args) {
1316 uint32_t request_id = GetNextRequestId();
1317 base::string16 search_text;
1318 blink::WebFindOptions options;
1319 if (!args->GetNext(&search_text) || search_text.empty()) {
1320 args->ThrowError("Must provide a non-empty search content");
1324 args->GetNext(&options);
1326 web_contents()->Find(request_id, search_text, options);
1330 void WebContents::StopFindInPage(content::StopFindAction action) {
1331 web_contents()->StopFinding(action);
1334 void WebContents::ShowDefinitionForSelection() {
1335 #if defined(OS_MACOSX)
1336 const auto view = web_contents()->GetRenderWidgetHostView();
1338 view->ShowDefinitionForSelection();
1342 void WebContents::CopyImageAt(int x, int y) {
1343 const auto host = web_contents()->GetMainFrame();
1345 host->CopyImageAt(x, y);
1348 void WebContents::Focus() {
1349 web_contents()->Focus();
1352 #if !defined(OS_MACOSX)
1353 bool WebContents::IsFocused() const {
1354 auto view = web_contents()->GetRenderWidgetHostView();
1355 if (!view) return false;
1357 if (GetType() != BACKGROUND_PAGE) {
1358 auto window = web_contents()->GetNativeView()->GetToplevelWindow();
1359 if (window && !window->IsVisible())
1363 return view->HasFocus();
1367 void WebContents::TabTraverse(bool reverse) {
1368 web_contents()->FocusThroughTabTraversal(reverse);
1371 bool WebContents::SendIPCMessage(bool all_frames,
1372 const base::string16& channel,
1373 const base::ListValue& args) {
1374 return Send(new AtomViewMsg_Message(routing_id(), all_frames, channel, args));
1377 void WebContents::SendInputEvent(v8::Isolate* isolate,
1378 v8::Local<v8::Value> input_event) {
1379 const auto view = web_contents()->GetRenderWidgetHostView();
1382 const auto host = view->GetRenderWidgetHost();
1386 int type = mate::GetWebInputEventType(isolate, input_event);
1387 if (blink::WebInputEvent::isMouseEventType(type)) {
1388 blink::WebMouseEvent mouse_event;
1389 if (mate::ConvertFromV8(isolate, input_event, &mouse_event)) {
1390 host->ForwardMouseEvent(mouse_event);
1393 } else if (blink::WebInputEvent::isKeyboardEventType(type)) {
1394 content::NativeWebKeyboardEvent keyboard_event;
1395 if (mate::ConvertFromV8(isolate, input_event, &keyboard_event)) {
1396 host->ForwardKeyboardEvent(keyboard_event);
1399 } else if (type == blink::WebInputEvent::MouseWheel) {
1400 blink::WebMouseWheelEvent mouse_wheel_event;
1401 if (mate::ConvertFromV8(isolate, input_event, &mouse_wheel_event)) {
1402 host->ForwardWheelEvent(mouse_wheel_event);
1407 isolate->ThrowException(v8::Exception::Error(mate::StringToV8(
1408 isolate, "Invalid event object")));
1411 void WebContents::BeginFrameSubscription(mate::Arguments* args) {
1412 bool only_dirty = false;
1413 FrameSubscriber::FrameCaptureCallback callback;
1415 args->GetNext(&only_dirty);
1416 if (!args->GetNext(&callback)) {
1421 const auto view = web_contents()->GetRenderWidgetHostView();
1423 std::unique_ptr<FrameSubscriber> frame_subscriber(new FrameSubscriber(
1424 isolate(), view, callback, only_dirty));
1425 view->BeginFrameSubscription(std::move(frame_subscriber));
1429 void WebContents::EndFrameSubscription() {
1430 const auto view = web_contents()->GetRenderWidgetHostView();
1432 view->EndFrameSubscription();
1435 void WebContents::StartDrag(const mate::Dictionary& item,
1436 mate::Arguments* args) {
1437 base::FilePath file;
1438 std::vector<base::FilePath> files;
1439 if (!item.Get("files", &files) && item.Get("file", &file)) {
1440 files.push_back(file);
1443 mate::Handle<NativeImage> icon;
1444 if (!item.Get("icon", &icon) && !file.empty()) {
1445 // TODO(zcbenz): Set default icon from file.
1449 if (icon.IsEmpty()) {
1450 args->ThrowError("Must specify 'icon' option");
1454 #if defined(OS_MACOSX)
1455 // NSWindow.dragImage requires a non-empty NSImage
1456 if (icon->image().IsEmpty()) {
1457 args->ThrowError("Must specify non-empty 'icon' option");
1463 if (!files.empty()) {
1464 base::MessageLoop::ScopedNestableTaskAllower allow(
1465 base::MessageLoop::current());
1466 DragFileItems(files, icon->image(), web_contents()->GetNativeView());
1468 args->ThrowError("Must specify either 'file' or 'files' option");
1472 void WebContents::CapturePage(mate::Arguments* args) {
1474 base::Callback<void(const gfx::Image&)> callback;
1476 if (!(args->Length() == 1 && args->GetNext(&callback)) &&
1477 !(args->Length() == 2 && args->GetNext(&rect)
1478 && args->GetNext(&callback))) {
1483 const auto view = web_contents()->GetRenderWidgetHostView();
1484 const auto host = view ? view->GetRenderWidgetHost() : nullptr;
1485 if (!view || !host) {
1486 callback.Run(gfx::Image());
1490 // Capture full page if user doesn't specify a |rect|.
1491 const gfx::Size view_size = rect.IsEmpty() ? view->GetViewBounds().size() :
1494 // By default, the requested bitmap size is the view size in screen
1495 // coordinates. However, if there's more pixel detail available on the
1496 // current system, increase the requested bitmap size to capture it all.
1497 gfx::Size bitmap_size = view_size;
1498 const gfx::NativeView native_view = view->GetNativeView();
1500 display::Screen::GetScreen()->GetDisplayNearestWindow(native_view)
1501 .device_scale_factor();
1503 bitmap_size = gfx::ScaleToCeiledSize(view_size, scale);
1505 host->CopyFromBackingStore(gfx::Rect(rect.origin(), view_size),
1507 base::Bind(&OnCapturePageDone, callback),
1508 kBGRA_8888_SkColorType);
1511 void WebContents::OnCursorChange(const content::WebCursor& cursor) {
1512 content::WebCursor::CursorInfo info;
1513 cursor.GetCursorInfo(&info);
1515 if (cursor.IsCustom()) {
1516 Emit("cursor-changed", CursorTypeToString(info),
1517 gfx::Image::CreateFrom1xBitmap(info.custom_image),
1518 info.image_scale_factor,
1519 gfx::Size(info.custom_image.width(), info.custom_image.height()),
1522 Emit("cursor-changed", CursorTypeToString(info));
1526 void WebContents::SetSize(const SetSizeParams& params) {
1527 if (guest_delegate_)
1528 guest_delegate_->SetSize(params);
1531 bool WebContents::IsGuest() const {
1532 return type_ == WEB_VIEW;
1535 bool WebContents::IsOffScreen() const {
1536 return type_ == OFF_SCREEN;
1539 void WebContents::OnPaint(const gfx::Rect& dirty_rect, const SkBitmap& bitmap) {
1540 mate::Handle<NativeImage> image =
1541 NativeImage::Create(isolate(), gfx::Image::CreateFrom1xBitmap(bitmap));
1542 Emit("paint", dirty_rect, image);
1545 void WebContents::StartPainting() {
1549 auto* osr_rwhv = static_cast<OffScreenRenderWidgetHostView*>(
1550 web_contents()->GetRenderWidgetHostView());
1552 osr_rwhv->SetPainting(true);
1555 void WebContents::StopPainting() {
1559 auto* osr_rwhv = static_cast<OffScreenRenderWidgetHostView*>(
1560 web_contents()->GetRenderWidgetHostView());
1562 osr_rwhv->SetPainting(false);
1565 bool WebContents::IsPainting() const {
1569 const auto* osr_rwhv = static_cast<OffScreenRenderWidgetHostView*>(
1570 web_contents()->GetRenderWidgetHostView());
1571 return osr_rwhv && osr_rwhv->IsPainting();
1574 void WebContents::SetFrameRate(int frame_rate) {
1578 auto* osr_rwhv = static_cast<OffScreenRenderWidgetHostView*>(
1579 web_contents()->GetRenderWidgetHostView());
1581 osr_rwhv->SetFrameRate(frame_rate);
1584 int WebContents::GetFrameRate() const {
1588 const auto* osr_rwhv = static_cast<OffScreenRenderWidgetHostView*>(
1589 web_contents()->GetRenderWidgetHostView());
1590 return osr_rwhv ? osr_rwhv->GetFrameRate() : 0;
1593 void WebContents::Invalidate() {
1594 if (IsOffScreen()) {
1595 auto* osr_rwhv = static_cast<OffScreenRenderWidgetHostView*>(
1596 web_contents()->GetRenderWidgetHostView());
1598 osr_rwhv->Invalidate();
1600 const auto window = owner_window();
1602 window->Invalidate();
1606 void WebContents::SetZoomLevel(double level) {
1607 zoom_controller_->SetZoomLevel(level);
1610 double WebContents::GetZoomLevel() {
1611 return zoom_controller_->GetZoomLevel();
1614 void WebContents::SetZoomFactor(double factor) {
1615 auto level = content::ZoomFactorToZoomLevel(factor);
1616 SetZoomLevel(level);
1619 double WebContents::GetZoomFactor() {
1620 auto level = GetZoomLevel();
1621 return content::ZoomLevelToZoomFactor(level);
1624 void WebContents::OnSetTemporaryZoomLevel(double level,
1625 IPC::Message* reply_msg) {
1626 zoom_controller_->SetTemporaryZoomLevel(level);
1627 double new_level = zoom_controller_->GetZoomLevel();
1628 AtomViewHostMsg_SetTemporaryZoomLevel::WriteReplyParams(reply_msg, new_level);
1632 void WebContents::OnGetZoomLevel(IPC::Message* reply_msg) {
1633 AtomViewHostMsg_GetZoomLevel::WriteReplyParams(reply_msg, GetZoomLevel());
1637 v8::Local<v8::Value> WebContents::GetWebPreferences(v8::Isolate* isolate) {
1638 WebContentsPreferences* web_preferences =
1639 WebContentsPreferences::FromWebContents(web_contents());
1640 return mate::ConvertToV8(isolate, *web_preferences->web_preferences());
1643 v8::Local<v8::Value> WebContents::GetOwnerBrowserWindow() {
1645 return Window::From(isolate(), owner_window());
1647 return v8::Null(isolate());
1650 int32_t WebContents::ID() const {
1651 return weak_map_id();
1654 v8::Local<v8::Value> WebContents::Session(v8::Isolate* isolate) {
1655 return v8::Local<v8::Value>::New(isolate, session_);
1658 content::WebContents* WebContents::HostWebContents() {
1661 return embedder_->web_contents();
1664 void WebContents::SetEmbedder(const WebContents* embedder) {
1666 NativeWindow* owner_window = nullptr;
1667 auto relay = NativeWindowRelay::FromWebContents(embedder->web_contents());
1669 owner_window = relay->window.get();
1672 SetOwnerWindow(owner_window);
1674 content::RenderWidgetHostView* rwhv =
1675 web_contents()->GetRenderWidgetHostView();
1683 v8::Local<v8::Value> WebContents::DevToolsWebContents(v8::Isolate* isolate) {
1684 if (devtools_web_contents_.IsEmpty())
1685 return v8::Null(isolate);
1687 return v8::Local<v8::Value>::New(isolate, devtools_web_contents_);
1690 v8::Local<v8::Value> WebContents::Debugger(v8::Isolate* isolate) {
1691 if (debugger_.IsEmpty()) {
1692 auto handle = atom::api::Debugger::Create(isolate, web_contents());
1693 debugger_.Reset(isolate, handle.ToV8());
1695 return v8::Local<v8::Value>::New(isolate, debugger_);
1699 void WebContents::BuildPrototype(v8::Isolate* isolate,
1700 v8::Local<v8::FunctionTemplate> prototype) {
1701 prototype->SetClassName(mate::StringToV8(isolate, "WebContents"));
1702 mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
1704 .SetMethod("getId", &WebContents::GetID)
1705 .SetMethod("getProcessId", &WebContents::GetProcessID)
1706 .SetMethod("equal", &WebContents::Equal)
1707 .SetMethod("_loadURL", &WebContents::LoadURL)
1708 .SetMethod("downloadURL", &WebContents::DownloadURL)
1709 .SetMethod("_getURL", &WebContents::GetURL)
1710 .SetMethod("getTitle", &WebContents::GetTitle)
1711 .SetMethod("isLoading", &WebContents::IsLoading)
1712 .SetMethod("isLoadingMainFrame", &WebContents::IsLoadingMainFrame)
1713 .SetMethod("isWaitingForResponse", &WebContents::IsWaitingForResponse)
1714 .SetMethod("_stop", &WebContents::Stop)
1715 .SetMethod("_goBack", &WebContents::GoBack)
1716 .SetMethod("_goForward", &WebContents::GoForward)
1717 .SetMethod("_goToOffset", &WebContents::GoToOffset)
1718 .SetMethod("isCrashed", &WebContents::IsCrashed)
1719 .SetMethod("setUserAgent", &WebContents::SetUserAgent)
1720 .SetMethod("getUserAgent", &WebContents::GetUserAgent)
1721 .SetMethod("savePage", &WebContents::SavePage)
1722 .SetMethod("openDevTools", &WebContents::OpenDevTools)
1723 .SetMethod("closeDevTools", &WebContents::CloseDevTools)
1724 .SetMethod("isDevToolsOpened", &WebContents::IsDevToolsOpened)
1725 .SetMethod("isDevToolsFocused", &WebContents::IsDevToolsFocused)
1726 .SetMethod("enableDeviceEmulation",
1727 &WebContents::EnableDeviceEmulation)
1728 .SetMethod("disableDeviceEmulation",
1729 &WebContents::DisableDeviceEmulation)
1730 .SetMethod("toggleDevTools", &WebContents::ToggleDevTools)
1731 .SetMethod("inspectElement", &WebContents::InspectElement)
1732 .SetMethod("setAudioMuted", &WebContents::SetAudioMuted)
1733 .SetMethod("isAudioMuted", &WebContents::IsAudioMuted)
1734 .SetMethod("undo", &WebContents::Undo)
1735 .SetMethod("redo", &WebContents::Redo)
1736 .SetMethod("cut", &WebContents::Cut)
1737 .SetMethod("copy", &WebContents::Copy)
1738 .SetMethod("paste", &WebContents::Paste)
1739 .SetMethod("pasteAndMatchStyle", &WebContents::PasteAndMatchStyle)
1740 .SetMethod("delete", &WebContents::Delete)
1741 .SetMethod("selectAll", &WebContents::SelectAll)
1742 .SetMethod("unselect", &WebContents::Unselect)
1743 .SetMethod("replace", &WebContents::Replace)
1744 .SetMethod("replaceMisspelling", &WebContents::ReplaceMisspelling)
1745 .SetMethod("findInPage", &WebContents::FindInPage)
1746 .SetMethod("stopFindInPage", &WebContents::StopFindInPage)
1747 .SetMethod("focus", &WebContents::Focus)
1748 .SetMethod("isFocused", &WebContents::IsFocused)
1749 .SetMethod("tabTraverse", &WebContents::TabTraverse)
1750 .SetMethod("_send", &WebContents::SendIPCMessage)
1751 .SetMethod("sendInputEvent", &WebContents::SendInputEvent)
1752 .SetMethod("beginFrameSubscription",
1753 &WebContents::BeginFrameSubscription)
1754 .SetMethod("endFrameSubscription", &WebContents::EndFrameSubscription)
1755 .SetMethod("startDrag", &WebContents::StartDrag)
1756 .SetMethod("setSize", &WebContents::SetSize)
1757 .SetMethod("isGuest", &WebContents::IsGuest)
1758 .SetMethod("isOffscreen", &WebContents::IsOffScreen)
1759 .SetMethod("startPainting", &WebContents::StartPainting)
1760 .SetMethod("stopPainting", &WebContents::StopPainting)
1761 .SetMethod("isPainting", &WebContents::IsPainting)
1762 .SetMethod("setFrameRate", &WebContents::SetFrameRate)
1763 .SetMethod("getFrameRate", &WebContents::GetFrameRate)
1764 .SetMethod("invalidate", &WebContents::Invalidate)
1765 .SetMethod("setZoomLevel", &WebContents::SetZoomLevel)
1766 .SetMethod("_getZoomLevel", &WebContents::GetZoomLevel)
1767 .SetMethod("setZoomFactor", &WebContents::SetZoomFactor)
1768 .SetMethod("_getZoomFactor", &WebContents::GetZoomFactor)
1769 .SetMethod("getType", &WebContents::GetType)
1770 .SetMethod("getWebPreferences", &WebContents::GetWebPreferences)
1771 .SetMethod("getOwnerBrowserWindow", &WebContents::GetOwnerBrowserWindow)
1772 .SetMethod("hasServiceWorker", &WebContents::HasServiceWorker)
1773 .SetMethod("unregisterServiceWorker",
1774 &WebContents::UnregisterServiceWorker)
1775 .SetMethod("inspectServiceWorker", &WebContents::InspectServiceWorker)
1776 .SetMethod("print", &WebContents::Print)
1777 .SetMethod("_printToPDF", &WebContents::PrintToPDF)
1778 .SetMethod("addWorkSpace", &WebContents::AddWorkSpace)
1779 .SetMethod("removeWorkSpace", &WebContents::RemoveWorkSpace)
1780 .SetMethod("showDefinitionForSelection",
1781 &WebContents::ShowDefinitionForSelection)
1782 .SetMethod("copyImageAt", &WebContents::CopyImageAt)
1783 .SetMethod("capturePage", &WebContents::CapturePage)
1784 .SetMethod("setEmbedder", &WebContents::SetEmbedder)
1785 .SetMethod("setWebRTCIPHandlingPolicy",
1786 &WebContents::SetWebRTCIPHandlingPolicy)
1787 .SetMethod("getWebRTCIPHandlingPolicy",
1788 &WebContents::GetWebRTCIPHandlingPolicy)
1789 .SetProperty("id", &WebContents::ID)
1790 .SetProperty("session", &WebContents::Session)
1791 .SetProperty("hostWebContents", &WebContents::HostWebContents)
1792 .SetProperty("devToolsWebContents", &WebContents::DevToolsWebContents)
1793 .SetProperty("debugger", &WebContents::Debugger);
1796 AtomBrowserContext* WebContents::GetBrowserContext() const {
1797 return static_cast<AtomBrowserContext*>(web_contents()->GetBrowserContext());
1800 void WebContents::OnRendererMessage(const base::string16& channel,
1801 const base::ListValue& args) {
1802 // webContents.emit(channel, new Event(), args...);
1803 Emit(base::UTF16ToUTF8(channel), args);
1806 void WebContents::OnRendererMessageSync(const base::string16& channel,
1807 const base::ListValue& args,
1808 IPC::Message* message) {
1809 // webContents.emit(channel, new Event(sender, message), args...);
1810 EmitWithSender(base::UTF16ToUTF8(channel), web_contents(), message, args);
1814 mate::Handle<WebContents> WebContents::CreateFrom(
1815 v8::Isolate* isolate, content::WebContents* web_contents) {
1816 // We have an existing WebContents object in JS.
1817 auto existing = TrackableObject::FromWrappedClass(isolate, web_contents);
1819 return mate::CreateHandle(isolate, static_cast<WebContents*>(existing));
1821 // Otherwise create a new WebContents wrapper object.
1822 return mate::CreateHandle(isolate, new WebContents(isolate, web_contents,
1826 mate::Handle<WebContents> WebContents::CreateFrom(
1827 v8::Isolate* isolate, content::WebContents* web_contents, Type type) {
1828 // Otherwise create a new WebContents wrapper object.
1829 return mate::CreateHandle(isolate, new WebContents(isolate, web_contents,
1834 mate::Handle<WebContents> WebContents::Create(
1835 v8::Isolate* isolate, const mate::Dictionary& options) {
1836 return mate::CreateHandle(isolate, new WebContents(isolate, options));
1845 using atom::api::WebContents;
1847 void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused,
1848 v8::Local<v8::Context> context, void* priv) {
1849 v8::Isolate* isolate = context->GetIsolate();
1850 mate::Dictionary dict(isolate, exports);
1851 dict.Set("WebContents", WebContents::GetConstructor(isolate)->GetFunction());
1852 dict.SetMethod("create", &WebContents::Create);
1853 dict.SetMethod("fromId", &mate::TrackableObject<WebContents>::FromWeakMapID);
1854 dict.SetMethod("getAllWebContents",
1855 &mate::TrackableObject<WebContents>::GetAll);
1860 NODE_MODULE_CONTEXT_AWARE_BUILTIN(atom_browser_web_contents, Initialize)