1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef CONTENT_PUBLIC_BROWSER_WEB_CONTENTS_H_
6 #define CONTENT_PUBLIC_BROWSER_WEB_CONTENTS_H_
10 #include "base/basictypes.h"
11 #include "base/callback_forward.h"
12 #include "base/files/file_path.h"
13 #include "base/process/kill.h"
14 #include "base/strings/string16.h"
15 #include "base/supports_user_data.h"
16 #include "content/common/content_export.h"
17 #include "content/public/browser/invalidate_type.h"
18 #include "content/public/browser/navigation_controller.h"
19 #include "content/public/browser/page_navigator.h"
20 #include "content/public/browser/save_page_type.h"
21 #include "content/public/browser/web_ui.h"
22 #include "content/public/common/stop_find_action.h"
23 #include "ipc/ipc_sender.h"
24 #include "third_party/skia/include/core/SkColor.h"
25 #include "ui/base/window_open_disposition.h"
26 #include "ui/gfx/geometry/rect.h"
27 #include "ui/gfx/native_widget_types.h"
29 #if defined(OS_ANDROID)
30 #include "base/android/scoped_java_ref.h"
34 class DictionaryValue
;
39 struct WebFindOptions
;
43 struct LoadStateWithParam
;
49 class BrowserPluginGuestDelegate
;
50 class InterstitialPage
;
52 class RenderFrameHost
;
53 class RenderProcessHost
;
55 class RenderWidgetHostView
;
57 class WebContentsDelegate
;
58 struct CustomContextMenuContext
;
61 struct RendererPreferences
;
63 // WebContents is the core class in content/. A WebContents renders web content
64 // (usually HTML) in a rectangular area.
66 // Instantiating one is simple:
67 // scoped_ptr<content::WebContents> web_contents(
68 // content::WebContents::Create(
69 // content::WebContents::CreateParams(browser_context)));
70 // gfx::NativeView view = web_contents->GetNativeView();
71 // // |view| is an HWND, NSView*, GtkWidget*, etc.; insert it into the view
72 // // hierarchy wherever it needs to go.
74 // That's it; go to your kitchen, grab a scone, and chill. WebContents will do
75 // all the multi-process stuff behind the scenes. More details are at
76 // http://www.chromium.org/developers/design-documents/multi-process-architecture .
78 // Each WebContents has exactly one NavigationController; each
79 // NavigationController belongs to one WebContents. The NavigationController can
80 // be obtained from GetController(), and is used to load URLs into the
81 // WebContents, navigate it backwards/forwards, etc. See navigation_controller.h
83 class WebContents
: public PageNavigator
,
85 public base::SupportsUserData
{
87 struct CONTENT_EXPORT CreateParams
{
88 explicit CreateParams(BrowserContext
* context
);
90 CreateParams(BrowserContext
* context
, SiteInstance
* site
);
92 BrowserContext
* browser_context
;
94 // Specifying a SiteInstance here is optional. It can be set to avoid an
95 // extra process swap if the first navigation is expected to require a
96 // privileged process.
97 SiteInstance
* site_instance
;
99 // The opener WebContents is the WebContents that initiated this request,
103 // If the opener is suppressed, then the new WebContents doesn't hold a
104 // reference to its opener.
105 bool opener_suppressed
;
107 // The routing ids of the RenderView and of the main RenderFrame. Either
108 // both must be provided, or both must be MSG_ROUTING_NONE to have the
109 // WebContents make the assignment.
111 int main_frame_routing_id
;
113 // Initial size of the new WebContent's view. Can be (0, 0) if not needed.
114 gfx::Size initial_size
;
116 // True if the contents should be initially hidden.
117 bool initially_hidden
;
119 // If non-null then this WebContents will be hosted by a BrowserPlugin.
120 BrowserPluginGuestDelegate
* guest_delegate
;
122 // Used to specify the location context which display the new view should
123 // belong. This can be nullptr if not needed.
124 gfx::NativeView context
;
126 // Used to specify that the new WebContents creation is driven by the
127 // renderer process. In this case, the renderer-side objects, such as
128 // RenderFrame, have already been created on the renderer side, and
129 // WebContents construction should take this into account.
130 bool renderer_initiated_creation
;
133 // Creates a new WebContents.
134 CONTENT_EXPORT
static WebContents
* Create(const CreateParams
& params
);
136 // Similar to Create() above but should be used when you need to prepopulate
137 // the SessionStorageNamespaceMap of the WebContents. This can happen if
138 // you duplicate a WebContents, try to reconstitute it from a saved state,
139 // or when you create a new WebContents based on another one (eg., when
140 // servicing a window.open() call).
142 // You do not want to call this. If you think you do, make sure you completely
143 // understand when SessionStorageNamespace objects should be cloned, why
144 // they should not be shared by multiple WebContents, and what bad things
145 // can happen if you share the object.
146 CONTENT_EXPORT
static WebContents
* CreateWithSessionStorage(
147 const CreateParams
& params
,
148 const SessionStorageNamespaceMap
& session_storage_namespace_map
);
150 // Returns a WebContents that wraps the RenderViewHost, or nullptr if the
151 // render view host's delegate isn't a WebContents.
152 CONTENT_EXPORT
static WebContents
* FromRenderViewHost(
153 const RenderViewHost
* rvh
);
155 CONTENT_EXPORT
static WebContents
* FromRenderFrameHost(RenderFrameHost
* rfh
);
157 ~WebContents() override
{}
159 // Intrinsic tab state -------------------------------------------------------
161 // Gets/Sets the delegate.
162 virtual WebContentsDelegate
* GetDelegate() = 0;
163 virtual void SetDelegate(WebContentsDelegate
* delegate
) = 0;
165 // Gets the controller for this WebContents.
166 virtual NavigationController
& GetController() = 0;
167 virtual const NavigationController
& GetController() const = 0;
169 // Returns the user browser context associated with this WebContents (via the
170 // NavigationController).
171 virtual content::BrowserContext
* GetBrowserContext() const = 0;
173 // Gets the URL that is currently being displayed, if there is one.
174 // This method is deprecated. DO NOT USE! Pick either |GetVisibleURL| or
175 // |GetLastCommittedURL| as appropriate.
176 virtual const GURL
& GetURL() const = 0;
178 // Gets the URL currently being displayed in the URL bar, if there is one.
179 // This URL might be a pending navigation that hasn't committed yet, so it is
180 // not guaranteed to match the current page in this WebContents. A typical
181 // example of this is interstitials, which show the URL of the new/loading
182 // page (active) but the security context is of the old page (last committed).
183 virtual const GURL
& GetVisibleURL() const = 0;
185 // Gets the last committed URL. It represents the current page that is
186 // displayed in this WebContents. It represents the current security
188 virtual const GURL
& GetLastCommittedURL() const = 0;
190 // Return the currently active RenderProcessHost and RenderViewHost. Each of
191 // these may change over time.
192 virtual RenderProcessHost
* GetRenderProcessHost() const = 0;
194 // Returns the main frame for the currently active view.
195 virtual RenderFrameHost
* GetMainFrame() = 0;
197 // Returns the focused frame for the currently active view.
198 virtual RenderFrameHost
* GetFocusedFrame() = 0;
200 // Calls |on_frame| for each frame in the currently active view.
201 // Note: The RenderFrameHost parameter is not guaranteed to have a live
202 // RenderFrame counterpart in the renderer process. Callbacks should check
203 // IsRenderFrameLive, as sending IPC messages to it in this case will fail
205 virtual void ForEachFrame(
206 const base::Callback
<void(RenderFrameHost
*)>& on_frame
) = 0;
208 // Sends the given IPC to all frames in the currently active view. This is a
209 // convenience method instead of calling ForEach.
210 virtual void SendToAllFrames(IPC::Message
* message
) = 0;
212 // Gets the current RenderViewHost for this tab.
213 virtual RenderViewHost
* GetRenderViewHost() const = 0;
215 // Gets the current RenderViewHost's routing id. Returns
216 // MSG_ROUTING_NONE when there is no RenderViewHost.
217 virtual int GetRoutingID() const = 0;
219 // Returns the currently active RenderWidgetHostView. This may change over
220 // time and can be nullptr (during setup and teardown).
221 virtual RenderWidgetHostView
* GetRenderWidgetHostView() const = 0;
223 // Returns the currently active fullscreen widget. If there is none, returns
225 virtual RenderWidgetHostView
* GetFullscreenRenderWidgetHostView() const = 0;
227 // Create a WebUI page for the given url. In most cases, this doesn't need to
228 // be called by embedders since content will create its own WebUI objects as
229 // necessary. However if the embedder wants to create its own WebUI object and
230 // keep track of it manually, it can use this.
231 virtual WebUI
* CreateWebUI(const GURL
& url
) = 0;
233 // Returns the committed WebUI if one exists, otherwise the pending one.
234 virtual WebUI
* GetWebUI() const = 0;
235 virtual WebUI
* GetCommittedWebUI() const = 0;
237 // Allows overriding the user agent used for NavigationEntries it owns.
238 virtual void SetUserAgentOverride(const std::string
& override
) = 0;
239 virtual const std::string
& GetUserAgentOverride() const = 0;
241 // Enable the accessibility tree for this WebContents in the renderer,
242 // but don't enable creating a native accessibility tree on the browser
244 virtual void EnableTreeOnlyAccessibilityMode() = 0;
246 // Returns true only if "tree only" accessibility mode is on.
247 virtual bool IsTreeOnlyAccessibilityModeForTesting() const = 0;
249 // Returns true only if complete accessibility mode is on, meaning there's
250 // both renderer accessibility, and a native browser accessibility tree.
251 virtual bool IsFullAccessibilityModeForTesting() const = 0;
254 virtual void SetParentNativeViewAccessible(
255 gfx::NativeViewAccessible accessible_parent
) = 0;
258 // Tab navigation state ------------------------------------------------------
260 // Returns the current navigation properties, which if a navigation is
261 // pending may be provisional (e.g., the navigation could result in a
262 // download, in which case the URL would revert to what it was previously).
263 virtual const base::string16
& GetTitle() const = 0;
265 // The max page ID for any page that the current SiteInstance has loaded in
266 // this WebContents. Page IDs are specific to a given SiteInstance and
267 // WebContents, corresponding to a specific RenderView in the renderer.
268 // Page IDs increase with each new page that is loaded by a tab.
269 virtual int32
GetMaxPageID() = 0;
271 // The max page ID for any page that the given SiteInstance has loaded in
273 virtual int32
GetMaxPageIDForSiteInstance(SiteInstance
* site_instance
) = 0;
275 // Returns the SiteInstance associated with the current page.
276 virtual SiteInstance
* GetSiteInstance() const = 0;
278 // Returns the SiteInstance for the pending navigation, if any. Otherwise
279 // returns the current SiteInstance.
280 virtual SiteInstance
* GetPendingSiteInstance() const = 0;
282 // Returns whether this WebContents is loading a resource.
283 virtual bool IsLoading() const = 0;
285 // Returns whether this WebContents is loading and and the load is to a
286 // different top-level document (rather than being a navigation within the
287 // same document). This being true implies that IsLoading() is also true.
288 virtual bool IsLoadingToDifferentDocument() const = 0;
290 // Returns whether this WebContents is waiting for a first-response for the
291 // main resource of the page.
292 virtual bool IsWaitingForResponse() const = 0;
294 // Returns the current load state and the URL associated with it.
295 virtual const net::LoadStateWithParam
& GetLoadState() const = 0;
296 virtual const base::string16
& GetLoadStateHost() const = 0;
298 // Returns the upload progress.
299 virtual uint64
GetUploadSize() const = 0;
300 virtual uint64
GetUploadPosition() const = 0;
302 // Returns a set of the site URLs currently committed in this tab.
303 virtual std::set
<GURL
> GetSitesInTab() const = 0;
305 // Returns the character encoding of the page.
306 virtual const std::string
& GetEncoding() const = 0;
308 // True if this is a secure page which displayed insecure content.
309 virtual bool DisplayedInsecureContent() const = 0;
311 // Internal state ------------------------------------------------------------
313 // Indicates whether the WebContents is being captured (e.g., for screenshots
314 // or mirroring). Increment calls must be balanced with an equivalent number
315 // of decrement calls. |capture_size| specifies the capturer's video
316 // resolution, but can be empty to mean "unspecified." The first screen
317 // capturer that provides a non-empty |capture_size| will override the value
318 // returned by GetPreferredSize() until all captures have ended.
319 virtual void IncrementCapturerCount(const gfx::Size
& capture_size
) = 0;
320 virtual void DecrementCapturerCount() = 0;
321 virtual int GetCapturerCount() const = 0;
323 // Indicates/Sets whether all audio output from this WebContents is muted.
324 virtual bool IsAudioMuted() const = 0;
325 virtual void SetAudioMuted(bool mute
) = 0;
327 // Indicates whether this tab should be considered crashed. The setter will
328 // also notify the delegate when the flag is changed.
329 virtual bool IsCrashed() const = 0;
330 virtual void SetIsCrashed(base::TerminationStatus status
, int error_code
) = 0;
332 virtual base::TerminationStatus
GetCrashedStatus() const = 0;
334 // Whether the tab is in the process of being destroyed.
335 virtual bool IsBeingDestroyed() const = 0;
337 // Convenience method for notifying the delegate of a navigation state
339 virtual void NotifyNavigationStateChanged(InvalidateTypes changed_flags
) = 0;
341 // Get the last time that the WebContents was made active (either when it was
342 // created or shown with WasShown()).
343 virtual base::TimeTicks
GetLastActiveTime() const = 0;
345 // Invoked when the WebContents becomes shown/hidden.
346 virtual void WasShown() = 0;
347 virtual void WasHidden() = 0;
349 // Returns true if the before unload and unload listeners need to be
350 // fired. The value of this changes over time. For example, if true and the
351 // before unload listener is executed and allows the user to exit, then this
353 virtual bool NeedToFireBeforeUnload() = 0;
355 // Runs the beforeunload handler for the main frame. See also ClosePage and
356 // SwapOut in RenderViewHost, which run the unload handler.
358 // |for_cross_site_transition| indicates whether this call is for the current
359 // frame during a cross-process navigation. False means we're closing the
362 // TODO(creis): We should run the beforeunload handler for every frame that
364 virtual void DispatchBeforeUnload(bool for_cross_site_transition
) = 0;
366 // Commands ------------------------------------------------------------------
368 // Stop any pending navigation.
369 virtual void Stop() = 0;
371 // Creates a new WebContents with the same state as this one. The returned
372 // heap-allocated pointer is owned by the caller.
373 virtual WebContents
* Clone() = 0;
375 // Reloads the focused frame.
376 virtual void ReloadFocusedFrame(bool ignore_cache
) = 0;
378 // Editing commands ----------------------------------------------------------
380 virtual void Undo() = 0;
381 virtual void Redo() = 0;
382 virtual void Cut() = 0;
383 virtual void Copy() = 0;
384 virtual void CopyToFindPboard() = 0;
385 virtual void Paste() = 0;
386 virtual void PasteAndMatchStyle() = 0;
387 virtual void Delete() = 0;
388 virtual void SelectAll() = 0;
389 virtual void Unselect() = 0;
391 // Replaces the currently selected word or a word around the cursor.
392 virtual void Replace(const base::string16
& word
) = 0;
394 // Replaces the misspelling in the current selection.
395 virtual void ReplaceMisspelling(const base::string16
& word
) = 0;
397 // Let the renderer know that the menu has been closed.
398 virtual void NotifyContextMenuClosed(
399 const CustomContextMenuContext
& context
) = 0;
401 // Executes custom context menu action that was provided from Blink.
402 virtual void ExecuteCustomContextMenuCommand(
403 int action
, const CustomContextMenuContext
& context
) = 0;
405 // Views and focus -----------------------------------------------------------
407 // Returns the native widget that contains the contents of the tab.
408 virtual gfx::NativeView
GetNativeView() = 0;
410 // Returns the native widget with the main content of the tab (i.e. the main
411 // render view host, though there may be many popups in the tab as children of
413 virtual gfx::NativeView
GetContentNativeView() = 0;
415 // Returns the outermost native view. This will be used as the parent for
417 virtual gfx::NativeWindow
GetTopLevelNativeWindow() = 0;
419 // Computes the rectangle for the native widget that contains the contents of
420 // the tab in the screen coordinate system.
421 virtual gfx::Rect
GetContainerBounds() = 0;
423 // Get the bounds of the View, relative to the parent.
424 virtual gfx::Rect
GetViewBounds() = 0;
426 // Returns the current drop data, if any.
427 virtual DropData
* GetDropData() = 0;
429 // Sets focus to the native widget for this tab.
430 virtual void Focus() = 0;
432 // Sets focus to the appropriate element when the WebContents is shown the
434 virtual void SetInitialFocus() = 0;
436 // Stores the currently focused view.
437 virtual void StoreFocus() = 0;
439 // Restores focus to the last focus view. If StoreFocus has not yet been
440 // invoked, SetInitialFocus is invoked.
441 virtual void RestoreFocus() = 0;
443 // Focuses the first (last if |reverse| is true) element in the page.
444 // Invoked when this tab is getting the focus through tab traversal (|reverse|
445 // is true when using Shift-Tab).
446 virtual void FocusThroughTabTraversal(bool reverse
) = 0;
448 // Interstitials -------------------------------------------------------------
450 // Various other systems need to know about our interstitials.
451 virtual bool ShowingInterstitialPage() const = 0;
453 // Returns the currently showing interstitial, nullptr if no interstitial is
455 virtual InterstitialPage
* GetInterstitialPage() const = 0;
457 // Misc state & callbacks ----------------------------------------------------
459 // Check whether we can do the saving page operation this page given its MIME
461 virtual bool IsSavable() = 0;
463 // Prepare for saving the current web page to disk.
464 virtual void OnSavePage() = 0;
466 // Save page with the main HTML file path, the directory for saving resources,
467 // and the save type: HTML only or complete web page. Returns true if the
468 // saving process has been initiated successfully.
469 virtual bool SavePage(const base::FilePath
& main_file
,
470 const base::FilePath
& dir_path
,
471 SavePageType save_type
) = 0;
473 // Saves the given frame's URL to the local filesystem..
474 virtual void SaveFrame(const GURL
& url
,
475 const Referrer
& referrer
) = 0;
477 // Generate an MHTML representation of the current page in the given file.
478 virtual void GenerateMHTML(
479 const base::FilePath
& file
,
480 const base::Callback
<void(
481 int64
/* size of the file */)>& callback
) = 0;
483 // Returns the contents MIME type after a navigation.
484 virtual const std::string
& GetContentsMimeType() const = 0;
486 // Returns true if this WebContents will notify about disconnection.
487 virtual bool WillNotifyDisconnection() const = 0;
489 // Override the encoding and reload the page by sending down
490 // ViewMsg_SetPageEncoding to the renderer. |UpdateEncoding| is kinda
491 // the opposite of this, by which 'browser' is notified of
492 // the encoding of the current tab from 'renderer' (determined by
493 // auto-detect, http header, meta, bom detection, etc).
494 virtual void SetOverrideEncoding(const std::string
& encoding
) = 0;
496 // Remove any user-defined override encoding and reload by sending down
497 // ViewMsg_ResetPageEncodingToDefault to the renderer.
498 virtual void ResetOverrideEncoding() = 0;
500 // Returns the settings which get passed to the renderer.
501 virtual content::RendererPreferences
* GetMutableRendererPrefs() = 0;
503 // Tells the tab to close now. The tab will take care not to close until it's
504 // out of nested message loops.
505 virtual void Close() = 0;
507 // A render view-originated drag has ended. Informs the render view host and
508 // WebContentsDelegate.
509 virtual void SystemDragEnded() = 0;
511 // Notification the user has made a gesture while focus was on the
512 // page. This is used to avoid uninitiated user downloads (aka carpet
513 // bombing), see DownloadRequestLimiter for details.
514 virtual void UserGestureDone() = 0;
516 // Indicates if this tab was explicitly closed by the user (control-w, close
517 // tab menu item...). This is false for actions that indirectly close the tab,
518 // such as closing the window. The setter is maintained by TabStripModel, and
519 // the getter only useful from within TAB_CLOSED notification
520 virtual void SetClosedByUserGesture(bool value
) = 0;
521 virtual bool GetClosedByUserGesture() const = 0;
523 // Opens view-source tab for this contents.
524 virtual void ViewSource() = 0;
526 virtual void ViewFrameSource(const GURL
& url
,
527 const PageState
& page_state
)= 0;
529 // Gets the minimum/maximum zoom percent.
530 virtual int GetMinimumZoomPercent() const = 0;
531 virtual int GetMaximumZoomPercent() const = 0;
533 // Gets the preferred size of the contents.
534 virtual gfx::Size
GetPreferredSize() const = 0;
536 // Called when the reponse to a pending mouse lock request has arrived.
537 // Returns true if |allowed| is true and the mouse has been successfully
539 virtual bool GotResponseToLockMouseRequest(bool allowed
) = 0;
541 // Called when the user has selected a color in the color chooser.
542 virtual void DidChooseColorInColorChooser(SkColor color
) = 0;
544 // Called when the color chooser has ended.
545 virtual void DidEndColorChooser() = 0;
547 // Returns true if the location bar should be focused by default rather than
548 // the page contents. The view calls this function when the tab is focused
549 // to see what it should do.
550 virtual bool FocusLocationBarByDefault() = 0;
552 // Does this have an opener associated with it?
553 virtual bool HasOpener() const = 0;
555 // Returns the opener if HasOpener() is true, or nullptr otherwise.
556 virtual WebContents
* GetOpener() const = 0;
558 typedef base::Callback
<void(
560 int, /* HTTP status code */
561 const GURL
&, /* image_url */
562 const std::vector
<SkBitmap
>&, /* bitmaps */
563 /* The sizes in pixel of the bitmaps before they were resized due to the
564 max bitmap size passed to DownloadImage(). Each entry in the bitmaps
565 vector corresponds to an entry in the sizes vector. If a bitmap was
566 resized, there should be a single returned bitmap. */
567 const std::vector
<gfx::Size
>&)>
568 ImageDownloadCallback
;
570 // Sends a request to download the given image |url| and returns the unique
571 // id of the download request. When the download is finished, |callback| will
572 // be called with the bitmaps received from the renderer. If |is_favicon| is
573 // true, the cookies are not sent and not accepted during download.
574 // Bitmaps with pixel sizes larger than |max_bitmap_size| are filtered out
575 // from the bitmap results. If there are no bitmap results <=
576 // |max_bitmap_size|, the smallest bitmap is resized to |max_bitmap_size| and
577 // is the only result. A |max_bitmap_size| of 0 means unlimited.
578 virtual int DownloadImage(const GURL
& url
,
580 uint32_t max_bitmap_size
,
581 const ImageDownloadCallback
& callback
) = 0;
583 // Returns true if the WebContents is responsible for displaying a subframe
584 // in a different process from its parent page.
585 // TODO: this doesn't really belong here. With site isolation, this should be
586 // removed since we can then embed iframes in different processes.
587 virtual bool IsSubframe() const = 0;
589 // Finds text on a page.
590 virtual void Find(int request_id
,
591 const base::string16
& search_text
,
592 const blink::WebFindOptions
& options
) = 0;
594 // Notifies the renderer that the user has closed the FindInPage window
595 // (and what action to take regarding the selection).
596 virtual void StopFinding(StopFindAction action
) = 0;
598 // Requests the renderer to insert CSS into the main frame's document.
599 virtual void InsertCSS(const std::string
& css
) = 0;
601 // Returns true if audio has recently been audible from the WebContents.
602 virtual bool WasRecentlyAudible() = 0;
604 typedef base::Callback
<void(const Manifest
&)> GetManifestCallback
;
606 // Requests the Manifest of the main frame's document.
607 virtual void GetManifest(const GetManifestCallback
&) = 0;
609 // Requests the renderer to exit fullscreen.
610 virtual void ExitFullscreen() = 0;
612 #if defined(OS_ANDROID)
613 CONTENT_EXPORT
static WebContents
* FromJavaWebContents(
614 jobject jweb_contents_android
);
615 virtual base::android::ScopedJavaLocalRef
<jobject
> GetJavaWebContents() = 0;
616 #elif defined(OS_MACOSX)
617 // Allowing other views disables optimizations which assume that only a single
618 // WebContents is present.
619 virtual void SetAllowOtherViews(bool allow
) = 0;
621 // Returns true if other views are allowed, false otherwise.
622 virtual bool GetAllowOtherViews() = 0;
626 // This interface should only be implemented inside content.
627 friend class WebContentsImpl
;
631 } // namespace content
633 #endif // CONTENT_PUBLIC_BROWSER_WEB_CONTENTS_H_