1 // Copyright (c) 2014 GitHub, Inc.
2 // Use of this source code is governed by the MIT license that can be
3 // found in the LICENSE file.
5 #include "atom/browser/api/atom_api_web_contents.h"
11 #include "atom/browser/api/atom_api_debugger.h"
12 #include "atom/browser/api/atom_api_session.h"
13 #include "atom/browser/api/atom_api_window.h"
14 #include "atom/browser/atom_browser_client.h"
15 #include "atom/browser/atom_browser_context.h"
16 #include "atom/browser/atom_browser_main_parts.h"
17 #include "atom/browser/browser.h"
18 #include "atom/browser/lib/bluetooth_chooser.h"
19 #include "atom/browser/native_window.h"
20 #include "atom/browser/net/atom_network_delegate.h"
21 #include "atom/browser/osr/osr_output_device.h"
22 #include "atom/browser/osr/osr_render_widget_host_view.h"
23 #include "atom/browser/osr/osr_web_contents_view.h"
24 #include "atom/browser/ui/drag_util.h"
25 #include "atom/browser/web_contents_permission_helper.h"
26 #include "atom/browser/web_contents_preferences.h"
27 #include "atom/browser/web_contents_zoom_controller.h"
28 #include "atom/browser/web_view_guest_delegate.h"
29 #include "atom/common/api/api_messages.h"
30 #include "atom/common/api/event_emitter_caller.h"
31 #include "atom/common/color_util.h"
32 #include "atom/common/mouse_util.h"
33 #include "atom/common/native_mate_converters/blink_converter.h"
34 #include "atom/common/native_mate_converters/callback.h"
35 #include "atom/common/native_mate_converters/content_converter.h"
36 #include "atom/common/native_mate_converters/file_path_converter.h"
37 #include "atom/common/native_mate_converters/gfx_converter.h"
38 #include "atom/common/native_mate_converters/gurl_converter.h"
39 #include "atom/common/native_mate_converters/image_converter.h"
40 #include "atom/common/native_mate_converters/net_converter.h"
41 #include "atom/common/native_mate_converters/string16_converter.h"
42 #include "atom/common/native_mate_converters/value_converter.h"
43 #include "atom/common/options_switches.h"
44 #include "base/strings/utf_string_conversions.h"
45 #include "base/threading/thread_task_runner_handle.h"
46 #include "brightray/browser/inspectable_web_contents.h"
47 #include "brightray/browser/inspectable_web_contents_view.h"
48 #include "chrome/browser/printing/print_preview_message_handler.h"
49 #include "chrome/browser/printing/print_view_manager_basic.h"
50 #include "chrome/browser/ssl/security_state_tab_helper.h"
51 #include "content/browser/frame_host/navigation_entry_impl.h"
52 #include "content/browser/renderer_host/render_widget_host_impl.h"
53 #include "content/browser/web_contents/web_contents_impl.h"
54 #include "content/common/view_messages.h"
55 #include "content/public/browser/favicon_status.h"
56 #include "content/public/browser/native_web_keyboard_event.h"
57 #include "content/public/browser/navigation_details.h"
58 #include "content/public/browser/navigation_entry.h"
59 #include "content/public/browser/navigation_handle.h"
60 #include "content/public/browser/notification_details.h"
61 #include "content/public/browser/notification_source.h"
62 #include "content/public/browser/notification_types.h"
63 #include "content/public/browser/plugin_service.h"
64 #include "content/public/browser/render_frame_host.h"
65 #include "content/public/browser/render_process_host.h"
66 #include "content/public/browser/render_view_host.h"
67 #include "content/public/browser/render_widget_host.h"
68 #include "content/public/browser/render_widget_host_view.h"
69 #include "content/public/browser/resource_request_details.h"
70 #include "content/public/browser/service_worker_context.h"
71 #include "content/public/browser/site_instance.h"
72 #include "content/public/browser/storage_partition.h"
73 #include "content/public/browser/web_contents.h"
74 #include "content/public/common/context_menu_params.h"
75 #include "native_mate/dictionary.h"
76 #include "native_mate/object_template_builder.h"
77 #include "net/url_request/url_request_context.h"
78 #include "third_party/WebKit/public/platform/WebInputEvent.h"
79 #include "third_party/WebKit/public/web/WebFindOptions.h"
80 #include "ui/display/screen.h"
83 #include "tizen/extensions/common/xwalk_extension_server.h"
86 #if !defined(OS_MACOSX) && !defined(USE_EFL)
87 #include "ui/aura/window.h"
90 #include "atom/common/node_includes.h"
94 struct PrintSettings {
96 bool print_background;
104 struct Converter<atom::SetSizeParams> {
105 static bool FromV8(v8::Isolate* isolate,
106 v8::Local<v8::Value> val,
107 atom::SetSizeParams* out) {
108 mate::Dictionary params;
109 if (!ConvertFromV8(isolate, val, ¶ms))
112 if (params.Get("enableAutoSize", &autosize))
113 out->enable_auto_size.reset(new bool(true));
115 if (params.Get("min", &size))
116 out->min_size.reset(new gfx::Size(size));
117 if (params.Get("max", &size))
118 out->max_size.reset(new gfx::Size(size));
119 if (params.Get("normal", &size))
120 out->normal_size.reset(new gfx::Size(size));
126 struct Converter<PrintSettings> {
127 static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val,
128 PrintSettings* out) {
129 mate::Dictionary dict;
130 if (!ConvertFromV8(isolate, val, &dict))
132 dict.Get("silent", &(out->silent));
133 dict.Get("printBackground", &(out->print_background));
139 struct Converter<WindowOpenDisposition> {
140 static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
141 WindowOpenDisposition val) {
142 std::string disposition = "other";
144 case WindowOpenDisposition::CURRENT_TAB:
145 disposition = "default";
147 case WindowOpenDisposition::NEW_FOREGROUND_TAB:
148 disposition = "foreground-tab";
150 case WindowOpenDisposition::NEW_BACKGROUND_TAB:
151 disposition = "background-tab";
153 case WindowOpenDisposition::NEW_POPUP:
154 case WindowOpenDisposition::NEW_WINDOW:
155 disposition = "new-window";
157 case WindowOpenDisposition::SAVE_TO_DISK:
158 disposition = "save-to-disk";
163 return mate::ConvertToV8(isolate, disposition);
168 struct Converter<content::SavePageType> {
169 static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val,
170 content::SavePageType* out) {
171 std::string save_type;
172 if (!ConvertFromV8(isolate, val, &save_type))
174 save_type = base::ToLowerASCII(save_type);
175 if (save_type == "htmlonly") {
176 *out = content::SAVE_PAGE_TYPE_AS_ONLY_HTML;
177 } else if (save_type == "htmlcomplete") {
178 *out = content::SAVE_PAGE_TYPE_AS_COMPLETE_HTML;
179 } else if (save_type == "mhtml") {
180 *out = content::SAVE_PAGE_TYPE_AS_MHTML;
189 struct Converter<atom::api::WebContents::Type> {
190 static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
191 atom::api::WebContents::Type val) {
192 using Type = atom::api::WebContents::Type;
193 std::string type = "";
195 case Type::BACKGROUND_PAGE: type = "backgroundPage"; break;
196 case Type::BROWSER_WINDOW: type = "window"; break;
197 case Type::BROWSER_VIEW: type = "browserView"; break;
198 case Type::REMOTE: type = "remote"; break;
199 case Type::WEB_VIEW: type = "webview"; break;
200 case Type::OFF_SCREEN: type = "offscreen"; break;
203 return mate::ConvertToV8(isolate, type);
206 static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val,
207 atom::api::WebContents::Type* out) {
208 using Type = atom::api::WebContents::Type;
210 if (!ConvertFromV8(isolate, val, &type))
212 if (type == "backgroundPage") {
213 *out = Type::BACKGROUND_PAGE;
214 } else if (type == "browserView") {
215 *out = Type::BROWSER_VIEW;
216 } else if (type == "webview") {
217 *out = Type::WEB_VIEW;
218 } else if (type == "offscreen") {
219 *out = Type::OFF_SCREEN;
236 content::ServiceWorkerContext* GetServiceWorkerContext(
237 const content::WebContents* web_contents) {
238 auto context = web_contents->GetBrowserContext();
239 auto site_instance = web_contents->GetSiteInstance();
240 if (!context || !site_instance)
243 auto storage_partition =
244 content::BrowserContext::GetStoragePartition(context, site_instance);
245 if (!storage_partition)
248 return storage_partition->GetServiceWorkerContext();
251 // Called when CapturePage is done.
252 void OnCapturePageDone(const base::Callback<void(const gfx::Image&)>& callback,
253 const SkBitmap& bitmap,
254 content::ReadbackResponse response) {
255 callback.Run(gfx::Image::CreateFrom1xBitmap(bitmap));
258 // Set the background color of RenderWidgetHostView.
259 void SetBackgroundColor(content::WebContents* web_contents) {
260 const auto view = web_contents->GetRenderWidgetHostView();
262 WebContentsPreferences* web_preferences =
263 WebContentsPreferences::FromWebContents(web_contents);
264 std::string color_name;
265 if (web_preferences->web_preferences()->GetString(options::kBackgroundColor,
267 view->SetBackgroundColor(ParseHexColor(color_name));
269 view->SetBackgroundColor(SK_ColorTRANSPARENT);
276 WebContents::WebContents(v8::Isolate* isolate,
277 content::WebContents* web_contents,
279 : content::WebContentsObserver(web_contents),
281 zoom_controller_(nullptr),
284 background_throttling_(true),
285 enable_devtools_(true) {
286 if (type == REMOTE) {
287 web_contents->SetUserAgentOverride(GetBrowserContext()->GetUserAgent());
289 AttachAsUserData(web_contents);
291 const mate::Dictionary options = mate::Dictionary::CreateEmpty(isolate);
292 auto session = Session::CreateFrom(isolate, GetBrowserContext());
293 session_.Reset(isolate, session.ToV8());
294 InitWithSessionAndOptions(isolate, web_contents, session, options);
298 WebContents::WebContents(v8::Isolate* isolate, const mate::Dictionary& options)
299 : embedder_(nullptr),
300 zoom_controller_(nullptr),
301 type_(BROWSER_WINDOW),
303 background_throttling_(true),
304 enable_devtools_(true) {
306 options.Get("backgroundThrottling", &background_throttling_);
308 // FIXME(zcbenz): We should read "type" parameter for better design, but
309 // on Windows we have encountered a compiler bug that if we read "type"
310 // from |options| and then set |type_|, a memory corruption will happen
311 // and Electron will soon crash.
312 // Remvoe this after we upgraded to use VS 2015 Update 3.
314 if (options.Get("isGuest", &b) && b)
316 else if (options.Get("isBackgroundPage", &b) && b)
317 type_ = BACKGROUND_PAGE;
318 else if (options.Get("isBrowserView", &b) && b)
319 type_ = BROWSER_VIEW;
320 else if (options.Get("offscreen", &b) && b)
323 // Whether to enable DevTools.
324 options.Get("devTools", &enable_devtools_);
326 // Obtain the session.
327 std::string partition;
328 mate::Handle<api::Session> session;
329 if (options.Get("session", &session)) {
330 } else if (options.Get("partition", &partition)) {
331 session = Session::FromPartition(isolate, partition);
333 // Use the default session if not specified.
334 session = Session::FromPartition(isolate, "");
336 session_.Reset(isolate, session.ToV8());
338 content::WebContents* web_contents;
340 scoped_refptr<content::SiteInstance> site_instance =
341 content::SiteInstance::CreateForURL(
342 session->browser_context(), GURL("chrome-guest://fake-host"));
343 content::WebContents::CreateParams params(
344 session->browser_context(), site_instance);
345 guest_delegate_.reset(new WebViewGuestDelegate);
346 params.guest_delegate = guest_delegate_.get();
347 web_contents = content::WebContents::Create(params);
348 } else if (IsOffScreen()) {
349 bool transparent = false;
350 options.Get("transparent", &transparent);
352 content::WebContents::CreateParams params(session->browser_context());
353 auto* view = new OffScreenWebContentsView(
354 transparent, base::Bind(&WebContents::OnPaint, base::Unretained(this)));
356 params.delegate_view = view;
358 web_contents = content::WebContents::Create(params);
359 view->SetWebContents(web_contents);
361 content::WebContents::CreateParams params(session->browser_context());
362 web_contents = content::WebContents::Create(params);
365 InitWithSessionAndOptions(isolate, web_contents, session, options);
368 void WebContents::InitWithSessionAndOptions(v8::Isolate* isolate,
369 content::WebContents *web_contents,
370 mate::Handle<api::Session> session,
371 const mate::Dictionary& options) {
372 content::WebContentsObserver::Observe(web_contents);
373 InitWithWebContents(web_contents, session->browser_context());
375 managed_web_contents()->GetView()->SetDelegate(this);
377 // Save the preferences in C++.
378 new WebContentsPreferences(web_contents, options);
380 // Initialize permission helper.
381 WebContentsPermissionHelper::CreateForWebContents(web_contents);
382 // Initialize security state client.
383 SecurityStateTabHelper::CreateForWebContents(web_contents);
384 // Initialize zoom controller.
385 WebContentsZoomController::CreateForWebContents(web_contents);
386 zoom_controller_ = WebContentsZoomController::FromWebContents(web_contents);
388 if (options.Get(options::kZoomFactor, &zoom_factor))
389 zoom_controller_->SetDefaultZoomFactor(zoom_factor);
391 web_contents->SetUserAgentOverride(GetBrowserContext()->GetUserAgent());
394 guest_delegate_->Initialize(this);
396 NativeWindow* owner_window = nullptr;
397 if (options.Get("embedder", &embedder_) && embedder_) {
398 // New WebContents's owner_window is the embedder's owner_window.
400 NativeWindowRelay::FromWebContents(embedder_->web_contents());
402 owner_window = relay->window.get();
405 SetOwnerWindow(owner_window);
408 const content::NavigationController* controller =
409 &web_contents->GetController();
410 registrar_.Add(this, content::NOTIFICATION_NAV_ENTRY_PENDING,
411 content::Source<content::NavigationController>(controller));
414 AttachAsUserData(web_contents);
417 WebContents::~WebContents() {
418 // The destroy() is called.
419 if (managed_web_contents()) {
420 // For webview we need to tell content module to do some cleanup work before
422 if (type_ == WEB_VIEW)
423 guest_delegate_->Destroy();
425 RenderViewDeleted(web_contents()->GetRenderViewHost());
426 DestroyWebContents();
430 void WebContents::DestroyWebContents() {
431 // This event is only for internal use, which is emitted when WebContents is
433 Emit("will-destroy");
434 ResetManagedWebContents();
437 bool WebContents::DidAddMessageToConsole(content::WebContents* source,
439 const base::string16& message,
441 const base::string16& source_id) {
442 if (type_ == BROWSER_WINDOW || type_ == OFF_SCREEN) {
443 LOG(ERROR) << "Console Message : " << message << ", source:" << source_id << " (" << line_no << ")";
446 Emit("console-message", level, message, line_no, source_id);
451 void WebContents::OnCreateWindow(
452 const GURL& target_url,
453 const std::string& frame_name,
454 WindowOpenDisposition disposition,
455 const std::vector<std::string>& features,
456 const scoped_refptr<content::ResourceRequestBodyImpl>& body) {
457 if (type_ == BROWSER_WINDOW || type_ == OFF_SCREEN)
458 Emit("-new-window", target_url, frame_name, disposition, features, body);
460 Emit("new-window", target_url, frame_name, disposition, features);
463 void WebContents::WebContentsCreated(content::WebContents* source_contents,
464 int opener_render_process_id,
465 int opener_render_frame_id,
466 const std::string& frame_name,
467 const GURL& target_url,
468 content::WebContents* new_contents) {
469 v8::Locker locker(isolate());
470 v8::HandleScope handle_scope(isolate());
471 auto api_web_contents = CreateFrom(isolate(), new_contents, BROWSER_WINDOW);
472 Emit("-web-contents-created", api_web_contents, target_url, frame_name);
475 void WebContents::AddNewContents(content::WebContents* source,
476 content::WebContents* new_contents,
477 WindowOpenDisposition disposition,
478 const gfx::Rect& initial_rect,
481 v8::Locker locker(isolate());
482 v8::HandleScope handle_scope(isolate());
483 auto api_web_contents = CreateFrom(isolate(), new_contents);
484 if (Emit("-add-new-contents", api_web_contents, disposition, user_gesture,
485 initial_rect.x(), initial_rect.y(), initial_rect.width(),
486 initial_rect.height())) {
487 api_web_contents->DestroyWebContents();
491 content::WebContents* WebContents::OpenURLFromTab(
492 content::WebContents* source,
493 const content::OpenURLParams& params) {
494 if (params.disposition != WindowOpenDisposition::CURRENT_TAB) {
495 if (type_ == BROWSER_WINDOW || type_ == OFF_SCREEN)
496 Emit("-new-window", params.url, "", params.disposition);
498 Emit("new-window", params.url, "", params.disposition);
502 // Give user a chance to cancel navigation.
503 if (Emit("will-navigate", params.url))
506 // Don't load the URL if the web contents was marked as destroyed from a
507 // will-navigate event listener
511 return CommonWebContentsDelegate::OpenURLFromTab(source, params);
514 void WebContents::BeforeUnloadFired(content::WebContents* tab,
516 bool* proceed_to_fire_unload) {
517 if (type_ == BROWSER_WINDOW || type_ == OFF_SCREEN)
518 *proceed_to_fire_unload = proceed;
520 *proceed_to_fire_unload = true;
523 void WebContents::MoveContents(content::WebContents* source,
524 const gfx::Rect& pos) {
528 void WebContents::CloseContents(content::WebContents* source) {
530 LOG(ERROR) << __FUNCTION__;
531 if ((type_ == BROWSER_WINDOW || type_ == OFF_SCREEN) && owner_window())
532 owner_window()->CloseContents(source);
535 void WebContents::ActivateContents(content::WebContents* source) {
539 void WebContents::UpdateTargetURL(content::WebContents* source,
541 Emit("update-target-url", url);
544 bool WebContents::IsPopupOrPanel(const content::WebContents* source) const {
545 return type_ == BROWSER_WINDOW;
548 void WebContents::HandleKeyboardEvent(
549 content::WebContents* source,
550 const content::NativeWebKeyboardEvent& event) {
551 if (type_ == WEB_VIEW && embedder_) {
552 // Send the unhandled keyboard events back to the embedder.
553 embedder_->HandleKeyboardEvent(source, event);
555 // Go to the default keyboard handling.
556 CommonWebContentsDelegate::HandleKeyboardEvent(source, event);
560 bool WebContents::PreHandleKeyboardEvent(
561 content::WebContents* source,
562 const content::NativeWebKeyboardEvent& event,
563 bool* is_keyboard_shortcut) {
564 if (event.type == blink::WebInputEvent::Type::RawKeyDown
565 || event.type == blink::WebInputEvent::Type::KeyUp)
566 return Emit("before-input-event", event);
571 void WebContents::EnterFullscreenModeForTab(content::WebContents* source,
572 const GURL& origin) {
573 auto permission_helper =
574 WebContentsPermissionHelper::FromWebContents(source);
575 auto callback = base::Bind(&WebContents::OnEnterFullscreenModeForTab,
576 base::Unretained(this), source, origin);
577 permission_helper->RequestFullscreenPermission(callback);
580 void WebContents::OnEnterFullscreenModeForTab(content::WebContents* source,
585 CommonWebContentsDelegate::EnterFullscreenModeForTab(source, origin);
586 Emit("enter-html-full-screen");
589 void WebContents::ExitFullscreenModeForTab(content::WebContents* source) {
590 CommonWebContentsDelegate::ExitFullscreenModeForTab(source);
591 Emit("leave-html-full-screen");
594 void WebContents::RendererUnresponsive(
595 content::WebContents* source,
596 const content::WebContentsUnresponsiveState& unresponsive_state) {
597 Emit("unresponsive");
598 if ((type_ == BROWSER_WINDOW || type_ == OFF_SCREEN) && owner_window())
599 owner_window()->RendererUnresponsive(source);
602 void WebContents::RendererResponsive(content::WebContents* source) {
604 if ((type_ == BROWSER_WINDOW || type_ == OFF_SCREEN) && owner_window())
605 owner_window()->RendererResponsive(source);
608 bool WebContents::HandleContextMenu(const content::ContextMenuParams& params) {
609 if (params.custom_context.is_pepper_menu) {
610 Emit("pepper-context-menu", std::make_pair(params, web_contents()));
611 web_contents()->NotifyContextMenuClosed(params.custom_context);
613 Emit("context-menu", std::make_pair(params, web_contents()));
619 bool WebContents::OnGoToEntryOffset(int offset) {
624 void WebContents::FindReply(content::WebContents* web_contents,
626 int number_of_matches,
627 const gfx::Rect& selection_rect,
628 int active_match_ordinal,
633 v8::Locker locker(isolate());
634 v8::HandleScope handle_scope(isolate());
635 mate::Dictionary result = mate::Dictionary::CreateEmpty(isolate());
636 result.Set("requestId", request_id);
637 result.Set("matches", number_of_matches);
638 result.Set("selectionArea", selection_rect);
639 result.Set("activeMatchOrdinal", active_match_ordinal);
640 result.Set("finalUpdate", final_update); // Deprecate after 2.0
641 Emit("found-in-page", result);
644 bool WebContents::CheckMediaAccessPermission(
645 content::WebContents* web_contents,
646 const GURL& security_origin,
647 content::MediaStreamType type) {
651 void WebContents::RequestMediaAccessPermission(
652 content::WebContents* web_contents,
653 const content::MediaStreamRequest& request,
654 const content::MediaResponseCallback& callback) {
655 auto permission_helper =
656 WebContentsPermissionHelper::FromWebContents(web_contents);
657 permission_helper->RequestMediaAccessPermission(request, callback);
660 void WebContents::RequestToLockMouse(
661 content::WebContents* web_contents,
663 bool last_unlocked_by_target) {
664 auto permission_helper =
665 WebContentsPermissionHelper::FromWebContents(web_contents);
666 permission_helper->RequestPointerLockPermission(user_gesture);
669 std::unique_ptr<content::BluetoothChooser> WebContents::RunBluetoothChooser(
670 content::RenderFrameHost* frame,
671 const content::BluetoothChooser::EventHandler& event_handler) {
672 std::unique_ptr<BluetoothChooser> bluetooth_chooser(
673 new BluetoothChooser(this, event_handler));
674 return std::move(bluetooth_chooser);
677 void WebContents::BeforeUnloadFired(const base::TimeTicks& proceed_time) {
678 // Do nothing, we override this method just to avoid compilation error since
679 // there are two virtual functions named BeforeUnloadFired.
682 void WebContents::RenderViewCreated(content::RenderViewHost* render_view_host) {
683 const auto impl = content::RenderWidgetHostImpl::FromID(
684 render_view_host->GetProcess()->GetID(),
685 render_view_host->GetRoutingID());
687 impl->disable_hidden_ = !background_throttling_;
688 atom::Browser::Get()->RenderViewCreated(render_view_host);
691 void WebContents::RenderViewDeleted(content::RenderViewHost* render_view_host) {
692 Emit("render-view-deleted", render_view_host->GetProcess()->GetID());
695 void WebContents::RenderProcessGone(base::TerminationStatus status) {
696 Emit("crashed", status == base::TERMINATION_STATUS_PROCESS_WAS_KILLED);
699 void WebContents::PluginCrashed(const base::FilePath& plugin_path,
700 base::ProcessId plugin_pid) {
701 content::WebPluginInfo info;
702 auto plugin_service = content::PluginService::GetInstance();
703 plugin_service->GetPluginInfoByPath(plugin_path, &info);
704 Emit("plugin-crashed", info.name, info.version);
707 void WebContents::MediaStartedPlaying(const MediaPlayerInfo& video_type,
708 const MediaPlayerId& id) {
709 Emit("media-started-playing");
712 void WebContents::MediaStoppedPlaying(const MediaPlayerInfo& video_type,
713 const MediaPlayerId& id) {
714 Emit("media-paused");
717 void WebContents::DidChangeThemeColor(SkColor theme_color) {
718 Emit("did-change-theme-color", atom::ToRGBHex(theme_color));
721 void WebContents::DocumentLoadedInFrame(
722 content::RenderFrameHost* render_frame_host) {
723 if (!render_frame_host->GetParent())
727 void WebContents::DidFinishLoad(content::RenderFrameHost* render_frame_host,
728 const GURL& validated_url) {
729 bool is_main_frame = !render_frame_host->GetParent();
730 Emit("did-frame-finish-load", is_main_frame);
733 Emit("did-finish-load");
736 void WebContents::DidFailLoad(content::RenderFrameHost* render_frame_host,
739 const base::string16& error_description,
740 bool was_ignored_by_handler) {
741 bool is_main_frame = !render_frame_host->GetParent();
742 Emit("did-fail-load", error_code, error_description, url, is_main_frame);
745 void WebContents::DidStartLoading() {
746 #if defined(OS_TIZEN)
747 if (owner_window() && !owner_window()->IsVisible()) {
748 std::string scheme = web_contents()->GetURL().scheme();
749 if (std::string::npos != scheme.find("http")) {
750 owner_window()->Show();
754 Emit("did-start-loading");
757 void WebContents::DidStopLoading() {
758 Emit("did-stop-loading");
761 void WebContents::DidGetResourceResponseStart(
762 const content::ResourceRequestDetails& details) {
763 Emit("did-get-response-details",
764 details.socket_address.IsEmpty(),
766 details.original_url,
767 details.http_response_code,
770 details.headers.get(),
771 ResourceTypeToString(details.resource_type));
774 void WebContents::DidGetRedirectForResourceRequest(
775 const content::ResourceRedirectDetails& details) {
776 Emit("did-get-redirect-request",
779 (details.resource_type == content::RESOURCE_TYPE_MAIN_FRAME),
780 details.http_response_code,
783 details.headers.get());
786 void WebContents::DidStartNavigation(
787 content::NavigationHandle* navigation_handle) {
788 if (!navigation_handle->IsInMainFrame() || navigation_handle->IsSamePage())
791 if (deferred_load_url_.id) {
792 auto web_contents = navigation_handle->GetWebContents();
793 auto& controller = web_contents->GetController();
794 int id = controller.GetPendingEntry()->GetUniqueID();
795 if (id == deferred_load_url_.id) {
796 if (!deferred_load_url_.params.url.is_empty()) {
797 auto params = deferred_load_url_.params;
798 deferred_load_url_.id = 0;
799 deferred_load_url_.params =
800 content::NavigationController::LoadURLParams(GURL());
801 controller.LoadURLWithParams(params);
802 SetBackgroundColor(web_contents);
804 deferred_load_url_.id = 0;
810 void WebContents::DidFinishNavigation(
811 content::NavigationHandle* navigation_handle) {
812 bool is_main_frame = navigation_handle->IsInMainFrame();
813 if (navigation_handle->HasCommitted() && !navigation_handle->IsErrorPage()) {
814 auto url = navigation_handle->GetURL();
815 bool is_in_page = navigation_handle->IsSamePage();
816 if (is_main_frame && !is_in_page) {
817 Emit("did-navigate", url);
818 } else if (is_in_page) {
819 Emit("did-navigate-in-page", url, is_main_frame);
822 auto url = navigation_handle->GetURL();
823 int code = navigation_handle->GetNetErrorCode();
824 auto description = net::ErrorToShortString(code);
825 Emit("did-fail-provisional-load", code, description, url, is_main_frame);
827 // Do not emit "did-fail-load" for canceled requests.
828 if (code != net::ERR_ABORTED)
829 Emit("did-fail-load", code, description, url, is_main_frame);
833 void WebContents::TitleWasSet(content::NavigationEntry* entry,
836 Emit("-page-title-updated", entry->GetTitle(), explicit_set);
838 Emit("-page-title-updated", "", explicit_set);
841 void WebContents::DidUpdateFaviconURL(
842 const std::vector<content::FaviconURL>& urls) {
843 std::set<GURL> unique_urls;
844 for (const auto& iter : urls) {
845 if (iter.icon_type != content::FaviconURL::FAVICON)
847 const GURL& url = iter.icon_url;
849 unique_urls.insert(url);
851 Emit("page-favicon-updated", unique_urls);
854 void WebContents::Observe(int type,
855 const content::NotificationSource& source,
856 const content::NotificationDetails& details) {
858 case content::NOTIFICATION_NAV_ENTRY_PENDING: {
859 content::NavigationEntry* entry =
860 content::Details<content::NavigationEntry>(details).ptr();
861 content::NavigationEntryImpl* entry_impl =
862 static_cast<content::NavigationEntryImpl*>(entry);
863 // In NavigatorImpl::DidStartMainFrameNavigation when there is no
864 // browser side pending entry available it creates a new one based
865 // on existing pending entry, hence we track the unique id here
866 // instead in WebContents::LoadURL with controller.GetPendingEntry()
867 // TODO(deepak1556): Remove once we have
868 // https://codereview.chromium.org/2661743002.
869 if (entry_impl->frame_tree_node_id() == -1) {
870 deferred_load_url_.id = entry->GetUniqueID();
880 void WebContents::DevToolsReloadPage() {
881 Emit("devtools-reload-page");
884 void WebContents::DevToolsFocused() {
885 Emit("devtools-focused");
888 void WebContents::DevToolsOpened() {
889 v8::Locker locker(isolate());
890 v8::HandleScope handle_scope(isolate());
891 auto handle = WebContents::CreateFrom(
892 isolate(), managed_web_contents()->GetDevToolsWebContents());
893 devtools_web_contents_.Reset(isolate(), handle.ToV8());
895 // Set inspected tabID.
896 base::FundamentalValue tab_id(ID());
897 managed_web_contents()->CallClientFunction(
898 "DevToolsAPI.setInspectedTabId", &tab_id, nullptr, nullptr);
900 // Inherit owner window in devtools.
902 handle->SetOwnerWindow(managed_web_contents()->GetDevToolsWebContents(),
905 Emit("devtools-opened");
908 void WebContents::DevToolsClosed() {
909 v8::Locker locker(isolate());
910 v8::HandleScope handle_scope(isolate());
911 devtools_web_contents_.Reset();
913 Emit("devtools-closed");
916 void WebContents::OnWrtPluginMessage(const Ewk_Wrt_Message_Data& data) {
917 Ewk_Wrt_Message_Data tmp = data;
918 HandleWrtPluginMessage(&tmp);
921 void WebContents::OnWrtPluginSyncMessage(const Ewk_Wrt_Message_Data& data,
922 IPC::Message* reply) {
923 Ewk_Wrt_Message_Data tmp = data;
924 HandleWrtPluginMessage(&tmp);
925 AtomHostMsg_WrtSyncMessage::WriteReplyParams(reply, tmp.value);
929 void WebContents::HandleWrtPluginMessage(Ewk_Wrt_Message_Data* msg) {
930 Eina_Stringshare* msg_type = ewk_ipc_wrt_message_data_type_get(msg);
931 LOG(INFO) << msg_type;
932 #define TYPE_BEGIN(x) (!strncmp(msg_type, x, strlen(x)))
933 #define TYPE_IS(x) (!strcmp(msg_type, x))
934 if (TYPE_BEGIN("xwalk://")) {
935 auto extension_server = extensions::XWalkExtensionServer::GetInstance();
936 extension_server->HandleIPCMessage(msg);
938 Eina_Stringshare* msg_id = msg->GetId();
939 Eina_Stringshare* msg_ref_id = msg->GetReferenceId();
940 Eina_Stringshare* msg_value = msg->GetValue();
941 if (TYPE_IS("tizen://exit")) {
942 atom::Browser::Get()->Quit();
945 eina_stringshare_del(msg_ref_id);
946 eina_stringshare_del(msg_id);
947 eina_stringshare_del(msg_value);
952 eina_stringshare_del(msg_type);
955 bool WebContents::OnMessageReceived(const IPC::Message& message) {
957 IPC_BEGIN_MESSAGE_MAP(WebContents, message)
958 IPC_MESSAGE_HANDLER_DELAY_REPLY(WrtViewMsg_GetCSP, OnGetContentSecurityPolicy)
959 IPC_MESSAGE_HANDLER(AtomViewHostMsg_Message, OnRendererMessage)
960 IPC_MESSAGE_HANDLER_DELAY_REPLY(AtomViewHostMsg_Message_Sync,
961 OnRendererMessageSync)
962 IPC_MESSAGE_HANDLER_DELAY_REPLY(AtomViewHostMsg_SetTemporaryZoomLevel,
963 OnSetTemporaryZoomLevel)
964 IPC_MESSAGE_HANDLER_DELAY_REPLY(AtomViewHostMsg_GetZoomLevel,
966 IPC_MESSAGE_HANDLER(AtomHostMsg_WrtMessage, OnWrtPluginMessage)
967 IPC_MESSAGE_HANDLER_DELAY_REPLY(AtomHostMsg_WrtSyncMessage, OnWrtPluginSyncMessage)
968 // FIXME: Disable OnCursorChange due to stach_chk_fail crash.
969 // IPC_MESSAGE_HANDLER_CODE(ViewHostMsg_SetCursor, OnCursorChange,
971 IPC_MESSAGE_UNHANDLED(handled = false)
972 IPC_END_MESSAGE_MAP()
977 // There are three ways of destroying a webContents:
978 // 1. call webContents.destroy();
979 // 2. garbage collection;
980 // 3. user closes the window of webContents;
981 // For webview only #1 will happen, for BrowserWindow both #1 and #3 may
982 // happen. The #2 should never happen for webContents, because webview is
983 // managed by GuestViewManager, and BrowserWindow's webContents is managed
985 // For #1, the destructor will do the cleanup work and we only need to make
986 // sure "destroyed" event is emitted. For #3, the content::WebContents will
987 // be destroyed on close, and WebContentsDestroyed would be called for it, so
988 // we need to make sure the api::WebContents is also deleted.
989 void WebContents::WebContentsDestroyed() {
990 // Cleanup relationships with other parts.
993 // We can not call Destroy here because we need to call Emit first, but we
994 // also do not want any method to be used, so just mark as destroyed here.
999 // Destroy the native class in next tick.
1000 base::ThreadTaskRunnerHandle::Get()->PostTask(
1001 FROM_HERE, GetDestroyClosure());
1004 void WebContents::NavigationEntryCommitted(
1005 const content::LoadCommittedDetails& details) {
1006 Emit("navigation-entry-commited", details.entry->GetURL(),
1007 details.is_in_page, details.did_replace_entry);
1010 int64_t WebContents::GetID() const {
1011 int64_t process_id = web_contents()->GetRenderProcessHost()->GetID();
1012 int64_t routing_id = web_contents()->GetRoutingID();
1013 int64_t rv = (process_id << 32) + routing_id;
1017 int WebContents::GetProcessID() const {
1018 return web_contents()->GetRenderProcessHost()->GetID();
1021 WebContents::Type WebContents::GetType() const {
1025 bool WebContents::Equal(const WebContents* web_contents) const {
1026 return GetID() == web_contents->GetID();
1029 void WebContents::LoadURL(const GURL& url, const mate::Dictionary& options) {
1030 if (!url.is_valid() || url.spec().size() > url::kMaxURLChars) {
1031 Emit("did-fail-load",
1032 static_cast<int>(net::ERR_INVALID_URL),
1033 net::ErrorToShortString(net::ERR_INVALID_URL),
1034 url.possibly_invalid_spec(),
1039 content::NavigationController::LoadURLParams params(url);
1042 if (options.Get("httpReferrer", &http_referrer))
1043 params.referrer = content::Referrer(http_referrer.GetAsReferrer(),
1044 blink::WebReferrerPolicyDefault);
1046 std::string user_agent;
1047 if (options.Get("userAgent", &user_agent))
1048 web_contents()->SetUserAgentOverride(user_agent);
1050 std::string extra_headers;
1051 if (options.Get("extraHeaders", &extra_headers))
1052 params.extra_headers = extra_headers;
1054 scoped_refptr<content::ResourceRequestBodyImpl> body;
1055 if (options.Get("postData", &body)) {
1056 params.post_data = body;
1057 params.load_type = content::NavigationController::LOAD_TYPE_HTTP_POST;
1060 GURL base_url_for_data_url;
1061 if (options.Get("baseURLForDataURL", &base_url_for_data_url)) {
1062 params.base_url_for_data_url = base_url_for_data_url;
1063 params.load_type = content::NavigationController::LOAD_TYPE_DATA;
1066 params.transition_type = ui::PAGE_TRANSITION_TYPED;
1067 params.should_clear_history_list = true;
1068 params.override_user_agent = content::NavigationController::UA_OVERRIDE_TRUE;
1070 if (deferred_load_url_.id) {
1071 deferred_load_url_.params = params;
1075 web_contents()->GetController().LoadURLWithParams(params);
1076 // We have to call it right after LoadURL because the RenderViewHost is only
1077 // created after loading a page.
1078 SetBackgroundColor(web_contents());
1081 void WebContents::DownloadURL(const GURL& url) {
1082 auto browser_context = web_contents()->GetBrowserContext();
1083 auto download_manager =
1084 content::BrowserContext::GetDownloadManager(browser_context);
1086 download_manager->DownloadUrl(
1087 content::DownloadUrlParameters::CreateForWebContentsMainFrame(
1088 web_contents(), url));
1091 GURL WebContents::GetURL() const {
1092 return web_contents()->GetURL();
1095 base::string16 WebContents::GetTitle() const {
1096 return web_contents()->GetTitle();
1099 bool WebContents::IsLoading() const {
1100 return web_contents()->IsLoading();
1103 bool WebContents::IsLoadingMainFrame() const {
1104 // Comparing site instances works because Electron always creates a new site
1105 // instance when navigating, regardless of origin. See AtomBrowserClient.
1106 return (web_contents()->GetLastCommittedURL().is_empty() ||
1107 web_contents()->GetSiteInstance() !=
1108 web_contents()->GetPendingSiteInstance()) && IsLoading();
1111 bool WebContents::IsWaitingForResponse() const {
1112 return web_contents()->IsWaitingForResponse();
1115 void WebContents::Stop() {
1116 LOG(ERROR) << __FUNCTION__;
1117 web_contents()->Stop();
1120 void WebContents::GoBack() {
1121 atom::AtomBrowserClient::SuppressRendererProcessRestartForOnce();
1122 web_contents()->GetController().GoBack();
1125 void WebContents::GoForward() {
1126 atom::AtomBrowserClient::SuppressRendererProcessRestartForOnce();
1127 web_contents()->GetController().GoForward();
1130 void WebContents::GoToOffset(int offset) {
1131 atom::AtomBrowserClient::SuppressRendererProcessRestartForOnce();
1132 web_contents()->GetController().GoToOffset(offset);
1135 const std::string WebContents::GetWebRTCIPHandlingPolicy() const {
1136 return web_contents()->
1137 GetMutableRendererPrefs()->webrtc_ip_handling_policy;
1140 void WebContents::SetWebRTCIPHandlingPolicy(
1141 const std::string& webrtc_ip_handling_policy) {
1142 if (GetWebRTCIPHandlingPolicy() == webrtc_ip_handling_policy)
1144 web_contents()->GetMutableRendererPrefs()->webrtc_ip_handling_policy =
1145 webrtc_ip_handling_policy;
1147 content::RenderViewHost* host = web_contents()->GetRenderViewHost();
1149 host->SyncRendererPrefs();
1152 bool WebContents::IsCrashed() const {
1153 return web_contents()->IsCrashed();
1156 void WebContents::SetUserAgent(const std::string& user_agent,
1157 mate::Arguments* args) {
1158 web_contents()->SetUserAgentOverride(user_agent);
1161 std::string WebContents::GetUserAgent() {
1162 return web_contents()->GetUserAgentOverride();
1165 bool WebContents::SavePage(const base::FilePath& full_file_path,
1166 const content::SavePageType& save_type,
1167 const SavePageHandler::SavePageCallback& callback) {
1168 auto handler = new SavePageHandler(web_contents(), callback);
1169 return handler->Handle(full_file_path, save_type);
1172 void WebContents::OpenDevTools(mate::Arguments* args) {
1173 if (type_ == REMOTE)
1176 if (!enable_devtools_)
1180 if (type_ == WEB_VIEW || !owner_window()) {
1182 } else if (args && args->Length() == 1) {
1183 bool detach = false;
1184 mate::Dictionary options;
1185 if (args->GetNext(&options)) {
1186 options.Get("mode", &state);
1188 // TODO(kevinsawicki) Remove in 2.0
1189 options.Get("detach", &detach);
1190 if (state.empty() && detach)
1194 managed_web_contents()->SetDockState(state);
1195 managed_web_contents()->ShowDevTools();
1198 void WebContents::CloseDevTools() {
1199 if (type_ == REMOTE)
1202 managed_web_contents()->CloseDevTools();
1205 bool WebContents::IsDevToolsOpened() {
1206 if (type_ == REMOTE)
1209 return managed_web_contents()->IsDevToolsViewShowing();
1212 bool WebContents::IsDevToolsFocused() {
1213 if (type_ == REMOTE)
1216 return managed_web_contents()->GetView()->IsDevToolsViewFocused();
1219 void WebContents::EnableDeviceEmulation(
1220 const blink::WebDeviceEmulationParams& params) {
1221 if (type_ == REMOTE)
1224 Send(new ViewMsg_EnableDeviceEmulation(routing_id(), params));
1227 void WebContents::DisableDeviceEmulation() {
1228 if (type_ == REMOTE)
1231 Send(new ViewMsg_DisableDeviceEmulation(routing_id()));
1234 void WebContents::ToggleDevTools() {
1235 if (IsDevToolsOpened())
1238 OpenDevTools(nullptr);
1241 void WebContents::InspectElement(int x, int y) {
1242 if (type_ == REMOTE)
1245 if (!enable_devtools_)
1248 if (!managed_web_contents()->GetDevToolsWebContents())
1249 OpenDevTools(nullptr);
1250 managed_web_contents()->InspectElement(x, y);
1253 void WebContents::InspectServiceWorker() {
1254 if (type_ == REMOTE)
1257 if (!enable_devtools_)
1260 for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) {
1261 if (agent_host->GetType() ==
1262 content::DevToolsAgentHost::kTypeServiceWorker) {
1263 OpenDevTools(nullptr);
1264 managed_web_contents()->AttachTo(agent_host);
1270 void WebContents::HasServiceWorker(
1271 const base::Callback<void(bool)>& callback) {
1272 auto context = GetServiceWorkerContext(web_contents());
1276 context->CheckHasServiceWorker(web_contents()->GetLastCommittedURL(),
1281 void WebContents::UnregisterServiceWorker(
1282 const base::Callback<void(bool)>& callback) {
1283 auto context = GetServiceWorkerContext(web_contents());
1287 context->UnregisterServiceWorker(web_contents()->GetLastCommittedURL(),
1291 void WebContents::SetAudioMuted(bool muted) {
1292 web_contents()->SetAudioMuted(muted);
1295 bool WebContents::IsAudioMuted() {
1296 return web_contents()->IsAudioMuted();
1299 void WebContents::Print(mate::Arguments* args) {
1300 PrintSettings settings = { false, false };
1301 if (args->Length() == 1 && !args->GetNext(&settings)) {
1306 printing::PrintViewManagerBasic::FromWebContents(web_contents())->
1307 PrintNow(web_contents()->GetMainFrame(),
1309 settings.print_background);
1312 void WebContents::PrintToPDF(const base::DictionaryValue& setting,
1313 const PrintToPDFCallback& callback) {
1314 printing::PrintPreviewMessageHandler::FromWebContents(web_contents())->
1315 PrintToPDF(setting, callback);
1318 void WebContents::AddWorkSpace(mate::Arguments* args,
1319 const base::FilePath& path) {
1321 args->ThrowError("path cannot be empty");
1324 DevToolsAddFileSystem(path);
1327 void WebContents::RemoveWorkSpace(mate::Arguments* args,
1328 const base::FilePath& path) {
1330 args->ThrowError("path cannot be empty");
1333 DevToolsRemoveFileSystem(path);
1336 void WebContents::Undo() {
1337 web_contents()->Undo();
1340 void WebContents::Redo() {
1341 web_contents()->Redo();
1344 void WebContents::Cut() {
1345 web_contents()->Cut();
1348 void WebContents::Copy() {
1349 web_contents()->Copy();
1352 void WebContents::Paste() {
1353 web_contents()->Paste();
1356 void WebContents::PasteAndMatchStyle() {
1357 web_contents()->PasteAndMatchStyle();
1360 void WebContents::Delete() {
1361 web_contents()->Delete();
1364 void WebContents::SelectAll() {
1365 web_contents()->SelectAll();
1368 void WebContents::Unselect() {
1369 web_contents()->Unselect();
1372 void WebContents::Replace(const base::string16& word) {
1373 web_contents()->Replace(word);
1376 void WebContents::ReplaceMisspelling(const base::string16& word) {
1377 web_contents()->ReplaceMisspelling(word);
1380 uint32_t WebContents::FindInPage(mate::Arguments* args) {
1381 uint32_t request_id = GetNextRequestId();
1382 base::string16 search_text;
1383 blink::WebFindOptions options;
1384 if (!args->GetNext(&search_text) || search_text.empty()) {
1385 args->ThrowError("Must provide a non-empty search content");
1389 args->GetNext(&options);
1391 web_contents()->Find(request_id, search_text, options);
1395 void WebContents::StopFindInPage(content::StopFindAction action) {
1396 web_contents()->StopFinding(action);
1399 void WebContents::ShowDefinitionForSelection() {
1400 #if defined(OS_MACOSX)
1401 const auto view = web_contents()->GetRenderWidgetHostView();
1403 view->ShowDefinitionForSelection();
1407 void WebContents::CopyImageAt(int x, int y) {
1408 const auto host = web_contents()->GetMainFrame();
1410 host->CopyImageAt(x, y);
1413 void WebContents::Focus() {
1414 web_contents()->Focus();
1417 #if !defined(OS_MACOSX)
1418 bool WebContents::IsFocused() const {
1419 auto view = web_contents()->GetRenderWidgetHostView();
1420 if (!view) return false;
1422 #if defined(USE_EFL)
1425 if (GetType() != BACKGROUND_PAGE) {
1426 auto window = web_contents()->GetNativeView()->GetToplevelWindow();
1427 if (window && !window->IsVisible())
1432 return view->HasFocus();
1436 void WebContents::TabTraverse(bool reverse) {
1437 web_contents()->FocusThroughTabTraversal(reverse);
1440 bool WebContents::SendIPCMessage(bool all_frames,
1441 const base::string16& channel,
1442 const base::ListValue& args) {
1443 return Send(new AtomViewMsg_Message(routing_id(), all_frames, channel, args));
1446 void WebContents::SendInputEvent(v8::Isolate* isolate,
1447 v8::Local<v8::Value> input_event) {
1448 const auto view = web_contents()->GetRenderWidgetHostView();
1451 const auto host = view->GetRenderWidgetHost();
1455 int type = mate::GetWebInputEventType(isolate, input_event);
1456 if (blink::WebInputEvent::isMouseEventType(type)) {
1457 blink::WebMouseEvent mouse_event;
1458 if (mate::ConvertFromV8(isolate, input_event, &mouse_event)) {
1459 host->ForwardMouseEvent(mouse_event);
1462 } else if (blink::WebInputEvent::isKeyboardEventType(type)) {
1463 content::NativeWebKeyboardEvent keyboard_event;
1464 if (mate::ConvertFromV8(isolate, input_event, &keyboard_event)) {
1465 host->ForwardKeyboardEvent(keyboard_event);
1468 } else if (type == blink::WebInputEvent::MouseWheel) {
1469 blink::WebMouseWheelEvent mouse_wheel_event;
1470 if (mate::ConvertFromV8(isolate, input_event, &mouse_wheel_event)) {
1471 host->ForwardWheelEvent(mouse_wheel_event);
1476 isolate->ThrowException(v8::Exception::Error(mate::StringToV8(
1477 isolate, "Invalid event object")));
1480 void WebContents::BeginFrameSubscription(mate::Arguments* args) {
1481 bool only_dirty = false;
1482 FrameSubscriber::FrameCaptureCallback callback;
1484 args->GetNext(&only_dirty);
1485 if (!args->GetNext(&callback)) {
1490 const auto view = web_contents()->GetRenderWidgetHostView();
1492 std::unique_ptr<FrameSubscriber> frame_subscriber(new FrameSubscriber(
1493 isolate(), view, callback, only_dirty));
1494 view->BeginFrameSubscription(std::move(frame_subscriber));
1498 void WebContents::EndFrameSubscription() {
1499 const auto view = web_contents()->GetRenderWidgetHostView();
1501 view->EndFrameSubscription();
1504 void WebContents::StartDrag(const mate::Dictionary& item,
1505 mate::Arguments* args) {
1506 base::FilePath file;
1507 std::vector<base::FilePath> files;
1508 if (!item.Get("files", &files) && item.Get("file", &file)) {
1509 files.push_back(file);
1512 mate::Handle<NativeImage> icon;
1513 if (!item.Get("icon", &icon) && !file.empty()) {
1514 // TODO(zcbenz): Set default icon from file.
1518 if (icon.IsEmpty()) {
1519 args->ThrowError("Must specify 'icon' option");
1523 #if defined(OS_MACOSX)
1524 // NSWindow.dragImage requires a non-empty NSImage
1525 if (icon->image().IsEmpty()) {
1526 args->ThrowError("Must specify non-empty 'icon' option");
1532 if (!files.empty()) {
1533 base::MessageLoop::ScopedNestableTaskAllower allow(
1534 base::MessageLoop::current());
1535 DragFileItems(files, icon->image(), web_contents()->GetNativeView());
1537 args->ThrowError("Must specify either 'file' or 'files' option");
1541 void WebContents::CapturePage(mate::Arguments* args) {
1543 base::Callback<void(const gfx::Image&)> callback;
1545 if (!(args->Length() == 1 && args->GetNext(&callback)) &&
1546 !(args->Length() == 2 && args->GetNext(&rect)
1547 && args->GetNext(&callback))) {
1552 const auto view = web_contents()->GetRenderWidgetHostView();
1553 const auto host = view ? view->GetRenderWidgetHost() : nullptr;
1554 if (!view || !host) {
1555 callback.Run(gfx::Image());
1559 // Capture full page if user doesn't specify a |rect|.
1560 const gfx::Size view_size = rect.IsEmpty() ? view->GetViewBounds().size() :
1563 // By default, the requested bitmap size is the view size in screen
1564 // coordinates. However, if there's more pixel detail available on the
1565 // current system, increase the requested bitmap size to capture it all.
1566 gfx::Size bitmap_size = view_size;
1567 const gfx::NativeView native_view = view->GetNativeView();
1569 display::Screen::GetScreen()->GetDisplayNearestWindow(native_view)
1570 .device_scale_factor();
1572 bitmap_size = gfx::ScaleToCeiledSize(view_size, scale);
1574 host->CopyFromBackingStore(gfx::Rect(rect.origin(), view_size),
1576 base::Bind(&OnCapturePageDone, callback),
1577 kBGRA_8888_SkColorType);
1580 void WebContents::OnCursorChange(const content::WebCursor& cursor) {
1581 content::WebCursor::CursorInfo info;
1582 cursor.GetCursorInfo(&info);
1584 if (cursor.IsCustom()) {
1585 Emit("cursor-changed", CursorTypeToString(info),
1586 gfx::Image::CreateFrom1xBitmap(info.custom_image),
1587 info.image_scale_factor,
1588 gfx::Size(info.custom_image.width(), info.custom_image.height()),
1591 Emit("cursor-changed", CursorTypeToString(info));
1595 void WebContents::SetSize(const SetSizeParams& params) {
1596 if (guest_delegate_)
1597 guest_delegate_->SetSize(params);
1600 bool WebContents::IsGuest() const {
1601 return type_ == WEB_VIEW;
1604 bool WebContents::IsOffScreen() const {
1605 return type_ == OFF_SCREEN;
1608 void WebContents::OnPaint(const gfx::Rect& dirty_rect, const SkBitmap& bitmap) {
1609 mate::Handle<NativeImage> image =
1610 NativeImage::Create(isolate(), gfx::Image::CreateFrom1xBitmap(bitmap));
1611 Emit("paint", dirty_rect, image);
1614 void WebContents::StartPainting() {
1618 auto* osr_rwhv = static_cast<OffScreenRenderWidgetHostView*>(
1619 web_contents()->GetRenderWidgetHostView());
1621 osr_rwhv->SetPainting(true);
1624 void WebContents::StopPainting() {
1628 auto* osr_rwhv = static_cast<OffScreenRenderWidgetHostView*>(
1629 web_contents()->GetRenderWidgetHostView());
1631 osr_rwhv->SetPainting(false);
1634 bool WebContents::IsPainting() const {
1638 const auto* osr_rwhv = static_cast<OffScreenRenderWidgetHostView*>(
1639 web_contents()->GetRenderWidgetHostView());
1640 return osr_rwhv && osr_rwhv->IsPainting();
1643 void WebContents::SetFrameRate(int frame_rate) {
1647 auto* osr_rwhv = static_cast<OffScreenRenderWidgetHostView*>(
1648 web_contents()->GetRenderWidgetHostView());
1650 osr_rwhv->SetFrameRate(frame_rate);
1653 int WebContents::GetFrameRate() const {
1657 const auto* osr_rwhv = static_cast<OffScreenRenderWidgetHostView*>(
1658 web_contents()->GetRenderWidgetHostView());
1659 return osr_rwhv ? osr_rwhv->GetFrameRate() : 0;
1662 void WebContents::Invalidate() {
1663 if (IsOffScreen()) {
1664 auto* osr_rwhv = static_cast<OffScreenRenderWidgetHostView*>(
1665 web_contents()->GetRenderWidgetHostView());
1667 osr_rwhv->Invalidate();
1669 const auto window = owner_window();
1671 window->Invalidate();
1675 void WebContents::SetZoomLevel(double level) {
1676 zoom_controller_->SetZoomLevel(level);
1679 double WebContents::GetZoomLevel() {
1680 return zoom_controller_->GetZoomLevel();
1683 void WebContents::SetZoomFactor(double factor) {
1684 auto level = content::ZoomFactorToZoomLevel(factor);
1685 SetZoomLevel(level);
1688 double WebContents::GetZoomFactor() {
1689 auto level = GetZoomLevel();
1690 return content::ZoomLevelToZoomFactor(level);
1693 void WebContents::OnSetTemporaryZoomLevel(double level,
1694 IPC::Message* reply_msg) {
1695 zoom_controller_->SetTemporaryZoomLevel(level);
1696 double new_level = zoom_controller_->GetZoomLevel();
1697 AtomViewHostMsg_SetTemporaryZoomLevel::WriteReplyParams(reply_msg, new_level);
1701 void WebContents::OnGetZoomLevel(IPC::Message* reply_msg) {
1702 AtomViewHostMsg_GetZoomLevel::WriteReplyParams(reply_msg, GetZoomLevel());
1706 void WebContents::OnGetContentSecurityPolicy(IPC::Message* reply_msg) {
1707 std::string csp_rule;
1708 std::string csp_report_rule;
1709 atom::Browser::Get()->GetCSP(csp_rule, csp_report_rule);
1710 WrtViewMsg_GetCSP::WriteReplyParams(reply_msg, csp_rule, csp_report_rule);
1714 v8::Local<v8::Value> WebContents::GetWebPreferences(v8::Isolate* isolate) {
1715 WebContentsPreferences* web_preferences =
1716 WebContentsPreferences::FromWebContents(web_contents());
1717 return mate::ConvertToV8(isolate, *web_preferences->web_preferences());
1720 v8::Local<v8::Value> WebContents::GetOwnerBrowserWindow() {
1722 return Window::From(isolate(), owner_window());
1724 return v8::Null(isolate());
1727 int32_t WebContents::ID() const {
1728 return weak_map_id();
1731 v8::Local<v8::Value> WebContents::Session(v8::Isolate* isolate) {
1732 return v8::Local<v8::Value>::New(isolate, session_);
1735 content::WebContents* WebContents::HostWebContents() {
1738 return embedder_->web_contents();
1741 void WebContents::SetEmbedder(const WebContents* embedder) {
1743 NativeWindow* owner_window = nullptr;
1744 auto relay = NativeWindowRelay::FromWebContents(embedder->web_contents());
1746 owner_window = relay->window.get();
1749 SetOwnerWindow(owner_window);
1751 content::RenderWidgetHostView* rwhv =
1752 web_contents()->GetRenderWidgetHostView();
1760 v8::Local<v8::Value> WebContents::DevToolsWebContents(v8::Isolate* isolate) {
1761 if (devtools_web_contents_.IsEmpty())
1762 return v8::Null(isolate);
1764 return v8::Local<v8::Value>::New(isolate, devtools_web_contents_);
1767 v8::Local<v8::Value> WebContents::Debugger(v8::Isolate* isolate) {
1768 if (debugger_.IsEmpty()) {
1769 auto handle = atom::api::Debugger::Create(isolate, web_contents());
1770 debugger_.Reset(isolate, handle.ToV8());
1772 return v8::Local<v8::Value>::New(isolate, debugger_);
1776 void WebContents::BuildPrototype(v8::Isolate* isolate,
1777 v8::Local<v8::FunctionTemplate> prototype) {
1778 prototype->SetClassName(mate::StringToV8(isolate, "WebContents"));
1779 mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
1781 .SetMethod("getId", &WebContents::GetID)
1782 .SetMethod("getProcessId", &WebContents::GetProcessID)
1783 .SetMethod("equal", &WebContents::Equal)
1784 .SetMethod("_loadURL", &WebContents::LoadURL)
1785 .SetMethod("downloadURL", &WebContents::DownloadURL)
1786 .SetMethod("_getURL", &WebContents::GetURL)
1787 .SetMethod("getTitle", &WebContents::GetTitle)
1788 .SetMethod("isLoading", &WebContents::IsLoading)
1789 .SetMethod("isLoadingMainFrame", &WebContents::IsLoadingMainFrame)
1790 .SetMethod("isWaitingForResponse", &WebContents::IsWaitingForResponse)
1791 .SetMethod("_stop", &WebContents::Stop)
1792 .SetMethod("_goBack", &WebContents::GoBack)
1793 .SetMethod("_goForward", &WebContents::GoForward)
1794 .SetMethod("_goToOffset", &WebContents::GoToOffset)
1795 .SetMethod("isCrashed", &WebContents::IsCrashed)
1796 .SetMethod("setUserAgent", &WebContents::SetUserAgent)
1797 .SetMethod("getUserAgent", &WebContents::GetUserAgent)
1798 .SetMethod("savePage", &WebContents::SavePage)
1799 .SetMethod("openDevTools", &WebContents::OpenDevTools)
1800 .SetMethod("closeDevTools", &WebContents::CloseDevTools)
1801 .SetMethod("isDevToolsOpened", &WebContents::IsDevToolsOpened)
1802 .SetMethod("isDevToolsFocused", &WebContents::IsDevToolsFocused)
1803 .SetMethod("enableDeviceEmulation",
1804 &WebContents::EnableDeviceEmulation)
1805 .SetMethod("disableDeviceEmulation",
1806 &WebContents::DisableDeviceEmulation)
1807 .SetMethod("toggleDevTools", &WebContents::ToggleDevTools)
1808 .SetMethod("inspectElement", &WebContents::InspectElement)
1809 .SetMethod("setAudioMuted", &WebContents::SetAudioMuted)
1810 .SetMethod("isAudioMuted", &WebContents::IsAudioMuted)
1811 .SetMethod("undo", &WebContents::Undo)
1812 .SetMethod("redo", &WebContents::Redo)
1813 .SetMethod("cut", &WebContents::Cut)
1814 .SetMethod("copy", &WebContents::Copy)
1815 .SetMethod("paste", &WebContents::Paste)
1816 .SetMethod("pasteAndMatchStyle", &WebContents::PasteAndMatchStyle)
1817 .SetMethod("delete", &WebContents::Delete)
1818 .SetMethod("selectAll", &WebContents::SelectAll)
1819 .SetMethod("unselect", &WebContents::Unselect)
1820 .SetMethod("replace", &WebContents::Replace)
1821 .SetMethod("replaceMisspelling", &WebContents::ReplaceMisspelling)
1822 .SetMethod("findInPage", &WebContents::FindInPage)
1823 .SetMethod("stopFindInPage", &WebContents::StopFindInPage)
1824 .SetMethod("focus", &WebContents::Focus)
1825 .SetMethod("isFocused", &WebContents::IsFocused)
1826 .SetMethod("tabTraverse", &WebContents::TabTraverse)
1827 .SetMethod("_send", &WebContents::SendIPCMessage)
1828 .SetMethod("sendInputEvent", &WebContents::SendInputEvent)
1829 .SetMethod("beginFrameSubscription",
1830 &WebContents::BeginFrameSubscription)
1831 .SetMethod("endFrameSubscription", &WebContents::EndFrameSubscription)
1832 .SetMethod("startDrag", &WebContents::StartDrag)
1833 .SetMethod("setSize", &WebContents::SetSize)
1834 .SetMethod("isGuest", &WebContents::IsGuest)
1835 .SetMethod("isOffscreen", &WebContents::IsOffScreen)
1836 .SetMethod("startPainting", &WebContents::StartPainting)
1837 .SetMethod("stopPainting", &WebContents::StopPainting)
1838 .SetMethod("isPainting", &WebContents::IsPainting)
1839 .SetMethod("setFrameRate", &WebContents::SetFrameRate)
1840 .SetMethod("getFrameRate", &WebContents::GetFrameRate)
1841 .SetMethod("invalidate", &WebContents::Invalidate)
1842 .SetMethod("setZoomLevel", &WebContents::SetZoomLevel)
1843 .SetMethod("_getZoomLevel", &WebContents::GetZoomLevel)
1844 .SetMethod("setZoomFactor", &WebContents::SetZoomFactor)
1845 .SetMethod("_getZoomFactor", &WebContents::GetZoomFactor)
1846 .SetMethod("getType", &WebContents::GetType)
1847 .SetMethod("getWebPreferences", &WebContents::GetWebPreferences)
1848 .SetMethod("getOwnerBrowserWindow", &WebContents::GetOwnerBrowserWindow)
1849 .SetMethod("hasServiceWorker", &WebContents::HasServiceWorker)
1850 .SetMethod("unregisterServiceWorker",
1851 &WebContents::UnregisterServiceWorker)
1852 .SetMethod("inspectServiceWorker", &WebContents::InspectServiceWorker)
1853 .SetMethod("print", &WebContents::Print)
1854 .SetMethod("_printToPDF", &WebContents::PrintToPDF)
1855 .SetMethod("addWorkSpace", &WebContents::AddWorkSpace)
1856 .SetMethod("removeWorkSpace", &WebContents::RemoveWorkSpace)
1857 .SetMethod("showDefinitionForSelection",
1858 &WebContents::ShowDefinitionForSelection)
1859 .SetMethod("copyImageAt", &WebContents::CopyImageAt)
1860 .SetMethod("capturePage", &WebContents::CapturePage)
1861 .SetMethod("setEmbedder", &WebContents::SetEmbedder)
1862 .SetMethod("setWebRTCIPHandlingPolicy",
1863 &WebContents::SetWebRTCIPHandlingPolicy)
1864 .SetMethod("getWebRTCIPHandlingPolicy",
1865 &WebContents::GetWebRTCIPHandlingPolicy)
1866 .SetProperty("id", &WebContents::ID)
1867 .SetProperty("session", &WebContents::Session)
1868 .SetProperty("hostWebContents", &WebContents::HostWebContents)
1869 .SetProperty("devToolsWebContents", &WebContents::DevToolsWebContents)
1870 .SetProperty("debugger", &WebContents::Debugger);
1873 AtomBrowserContext* WebContents::GetBrowserContext() const {
1874 return static_cast<AtomBrowserContext*>(web_contents()->GetBrowserContext());
1877 void WebContents::OnRendererMessage(const base::string16& channel,
1878 const base::ListValue& args) {
1879 // webContents.emit(channel, new Event(), args...);
1880 Emit(base::UTF16ToUTF8(channel), args);
1883 void WebContents::OnRendererMessageSync(const base::string16& channel,
1884 const base::ListValue& args,
1885 IPC::Message* message) {
1886 // webContents.emit(channel, new Event(sender, message), args...);
1887 EmitWithSender(base::UTF16ToUTF8(channel), web_contents(), message, args);
1891 mate::Handle<WebContents> WebContents::CreateFrom(
1892 v8::Isolate* isolate, content::WebContents* web_contents) {
1893 // We have an existing WebContents object in JS.
1894 auto existing = TrackableObject::FromWrappedClass(isolate, web_contents);
1896 return mate::CreateHandle(isolate, static_cast<WebContents*>(existing));
1898 // Otherwise create a new WebContents wrapper object.
1899 return mate::CreateHandle(isolate, new WebContents(isolate, web_contents,
1903 mate::Handle<WebContents> WebContents::CreateFrom(
1904 v8::Isolate* isolate, content::WebContents* web_contents, Type type) {
1905 // Otherwise create a new WebContents wrapper object.
1906 return mate::CreateHandle(isolate, new WebContents(isolate, web_contents,
1911 mate::Handle<WebContents> WebContents::Create(
1912 v8::Isolate* isolate, const mate::Dictionary& options) {
1913 return mate::CreateHandle(isolate, new WebContents(isolate, options));
1922 using atom::api::WebContents;
1924 void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused,
1925 v8::Local<v8::Context> context, void* priv) {
1926 v8::Isolate* isolate = context->GetIsolate();
1927 mate::Dictionary dict(isolate, exports);
1928 dict.Set("WebContents", WebContents::GetConstructor(isolate)->GetFunction());
1929 dict.SetMethod("create", &WebContents::Create);
1930 dict.SetMethod("fromId", &mate::TrackableObject<WebContents>::FromWeakMapID);
1931 dict.SetMethod("getAllWebContents",
1932 &mate::TrackableObject<WebContents>::GetAll);
1937 NODE_MODULE_CONTEXT_AWARE_BUILTIN(atom_browser_web_contents, Initialize)