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/navigation_controller.h"
18 #include "content/public/browser/page_navigator.h"
19 #include "content/public/browser/save_page_type.h"
20 #include "content/public/browser/web_ui.h"
21 #include "content/public/common/stop_find_action.h"
22 #include "ipc/ipc_sender.h"
23 #include "third_party/skia/include/core/SkColor.h"
24 #include "ui/base/window_open_disposition.h"
25 #include "ui/gfx/native_widget_types.h"
26 #include "ui/gfx/rect.h"
28 #if defined(OS_ANDROID)
29 #include "base/android/scoped_java_ref.h"
37 struct WebFindOptions
;
41 struct LoadStateWithParam
;
47 class InterstitialPage
;
49 class RenderFrameHost
;
50 class RenderProcessHost
;
52 class RenderWidgetHostView
;
54 class WebContentsDelegate
;
55 struct CustomContextMenuContext
;
57 struct RendererPreferences
;
59 // WebContents is the core class in content/. A WebContents renders web content
60 // (usually HTML) in a rectangular area.
62 // Instantiating one is simple:
63 // scoped_ptr<content::WebContents> web_contents(
64 // content::WebContents::Create(
65 // content::WebContents::CreateParams(browser_context)));
66 // gfx::NativeView view = web_contents->GetNativeView();
67 // // |view| is an HWND, NSView*, GtkWidget*, etc.; insert it into the view
68 // // hierarchy wherever it needs to go.
70 // That's it; go to your kitchen, grab a scone, and chill. WebContents will do
71 // all the multi-process stuff behind the scenes. More details are at
72 // http://www.chromium.org/developers/design-documents/multi-process-architecture .
74 // Each WebContents has exactly one NavigationController; each
75 // NavigationController belongs to one WebContents. The NavigationController can
76 // be obtained from GetController(), and is used to load URLs into the
77 // WebContents, navigate it backwards/forwards, etc. See navigation_controller.h
79 class WebContents
: public PageNavigator
,
81 public base::SupportsUserData
{
83 struct CONTENT_EXPORT CreateParams
{
84 explicit CreateParams(BrowserContext
* context
);
85 CreateParams(BrowserContext
* context
, SiteInstance
* site
);
87 BrowserContext
* browser_context
;
89 // Specifying a SiteInstance here is optional. It can be set to avoid an
90 // extra process swap if the first navigation is expected to require a
91 // privileged process.
92 SiteInstance
* site_instance
;
96 int main_frame_routing_id
;
98 // Initial size of the new WebContent's view. Can be (0, 0) if not needed.
99 gfx::Size initial_size
;
101 // True if the contents should be initially hidden.
102 bool initially_hidden
;
104 // Used to specify the location context which display the new view should
105 // belong. This can be NULL if not needed.
106 gfx::NativeView context
;
109 // Creates a new WebContents.
110 CONTENT_EXPORT
static WebContents
* Create(const CreateParams
& params
);
112 // Similar to Create() above but should be used when you need to prepopulate
113 // the SessionStorageNamespaceMap of the WebContents. This can happen if
114 // you duplicate a WebContents, try to reconstitute it from a saved state,
115 // or when you create a new WebContents based on another one (eg., when
116 // servicing a window.open() call).
118 // You do not want to call this. If you think you do, make sure you completely
119 // understand when SessionStorageNamespace objects should be cloned, why
120 // they should not be shared by multiple WebContents, and what bad things
121 // can happen if you share the object.
122 CONTENT_EXPORT
static WebContents
* CreateWithSessionStorage(
123 const CreateParams
& params
,
124 const SessionStorageNamespaceMap
& session_storage_namespace_map
);
126 // Returns a WebContents that wraps the RenderViewHost, or NULL if the
127 // render view host's delegate isn't a WebContents.
128 CONTENT_EXPORT
static WebContents
* FromRenderViewHost(
129 const RenderViewHost
* rvh
);
131 CONTENT_EXPORT
static WebContents
* FromRenderFrameHost(RenderFrameHost
* rfh
);
133 virtual ~WebContents() {}
135 // Intrinsic tab state -------------------------------------------------------
137 // Gets/Sets the delegate.
138 virtual WebContentsDelegate
* GetDelegate() = 0;
139 virtual void SetDelegate(WebContentsDelegate
* delegate
) = 0;
141 // Gets the controller for this WebContents.
142 virtual NavigationController
& GetController() = 0;
143 virtual const NavigationController
& GetController() const = 0;
145 // Returns the user browser context associated with this WebContents (via the
146 // NavigationController).
147 virtual content::BrowserContext
* GetBrowserContext() const = 0;
149 // Gets the URL that is currently being displayed, if there is one.
150 // This method is deprecated. DO NOT USE! Pick either |GetVisibleURL| or
151 // |GetLastCommittedURL| as appropriate.
152 virtual const GURL
& GetURL() const = 0;
154 // Gets the URL currently being displayed in the URL bar, if there is one.
155 // This URL might be a pending navigation that hasn't committed yet, so it is
156 // not guaranteed to match the current page in this WebContents. A typical
157 // example of this is interstitials, which show the URL of the new/loading
158 // page (active) but the security context is of the old page (last committed).
159 virtual const GURL
& GetVisibleURL() const = 0;
161 // Gets the last committed URL. It represents the current page that is
162 // displayed in this WebContents. It represents the current security
164 virtual const GURL
& GetLastCommittedURL() const = 0;
166 // Return the currently active RenderProcessHost and RenderViewHost. Each of
167 // these may change over time.
168 virtual RenderProcessHost
* GetRenderProcessHost() const = 0;
170 // Returns the main frame for the currently active view.
171 virtual RenderFrameHost
* GetMainFrame() = 0;
173 // Returns the focused frame for the currently active view.
174 virtual RenderFrameHost
* GetFocusedFrame() = 0;
176 // Calls |on_frame| for each frame in the currently active view.
177 virtual void ForEachFrame(
178 const base::Callback
<void(RenderFrameHost
*)>& on_frame
) = 0;
180 // Sends the given IPC to all frames in the currently active view. This is a
181 // convenience method instead of calling ForEach.
182 virtual void SendToAllFrames(IPC::Message
* message
) = 0;
184 // Gets the current RenderViewHost for this tab.
185 virtual RenderViewHost
* GetRenderViewHost() const = 0;
187 // Returns the WebContents embedding this WebContents, if any.
188 // If this is a top-level WebContents then it returns NULL.
189 virtual WebContents
* GetEmbedderWebContents() const = 0;
191 // Gets the instance ID of the current WebContents if it is embedded
192 // within a BrowserPlugin. The instance ID of a WebContents uniquely
193 // identifies it within its embedder WebContents.
194 virtual int GetEmbeddedInstanceID() const = 0;
196 // Gets the current RenderViewHost's routing id. Returns
197 // MSG_ROUTING_NONE when there is no RenderViewHost.
198 virtual int GetRoutingID() const = 0;
200 // Returns the currently active RenderWidgetHostView. This may change over
201 // time and can be NULL (during setup and teardown).
202 virtual RenderWidgetHostView
* GetRenderWidgetHostView() const = 0;
204 // Returns the currently active fullscreen widget. If there is none, returns
206 virtual RenderWidgetHostView
* GetFullscreenRenderWidgetHostView() const = 0;
208 // Create a WebUI page for the given url. In most cases, this doesn't need to
209 // be called by embedders since content will create its own WebUI objects as
210 // necessary. However if the embedder wants to create its own WebUI object and
211 // keep track of it manually, it can use this.
212 virtual WebUI
* CreateWebUI(const GURL
& url
) = 0;
214 // Returns the committed WebUI if one exists, otherwise the pending one.
215 virtual WebUI
* GetWebUI() const = 0;
216 virtual WebUI
* GetCommittedWebUI() const = 0;
218 // Allows overriding the user agent used for NavigationEntries it owns.
219 virtual void SetUserAgentOverride(const std::string
& override
) = 0;
220 virtual const std::string
& GetUserAgentOverride() const = 0;
223 virtual void SetParentNativeViewAccessible(
224 gfx::NativeViewAccessible accessible_parent
) = 0;
227 // Tab navigation state ------------------------------------------------------
229 // Returns the current navigation properties, which if a navigation is
230 // pending may be provisional (e.g., the navigation could result in a
231 // download, in which case the URL would revert to what it was previously).
232 virtual const base::string16
& GetTitle() const = 0;
234 // The max page ID for any page that the current SiteInstance has loaded in
235 // this WebContents. Page IDs are specific to a given SiteInstance and
236 // WebContents, corresponding to a specific RenderView in the renderer.
237 // Page IDs increase with each new page that is loaded by a tab.
238 virtual int32
GetMaxPageID() = 0;
240 // The max page ID for any page that the given SiteInstance has loaded in
242 virtual int32
GetMaxPageIDForSiteInstance(SiteInstance
* site_instance
) = 0;
244 // Returns the SiteInstance associated with the current page.
245 virtual SiteInstance
* GetSiteInstance() const = 0;
247 // Returns the SiteInstance for the pending navigation, if any. Otherwise
248 // returns the current SiteInstance.
249 virtual SiteInstance
* GetPendingSiteInstance() const = 0;
251 // Return whether this WebContents is loading a resource.
252 virtual bool IsLoading() const = 0;
254 // Returns whether this WebContents is waiting for a first-response for the
255 // main resource of the page.
256 virtual bool IsWaitingForResponse() const = 0;
258 // Return the current load state and the URL associated with it.
259 virtual const net::LoadStateWithParam
& GetLoadState() const = 0;
260 virtual const base::string16
& GetLoadStateHost() const = 0;
262 // Return the upload progress.
263 virtual uint64
GetUploadSize() const = 0;
264 virtual uint64
GetUploadPosition() const = 0;
266 // Returns a set of the site URLs currently committed in this tab.
267 virtual std::set
<GURL
> GetSitesInTab() const = 0;
269 // Return the character encoding of the page.
270 virtual const std::string
& GetEncoding() const = 0;
272 // True if this is a secure page which displayed insecure content.
273 virtual bool DisplayedInsecureContent() const = 0;
275 // Internal state ------------------------------------------------------------
277 // Indicates whether the WebContents is being captured (e.g., for screenshots
278 // or mirroring). Increment calls must be balanced with an equivalent number
279 // of decrement calls. |capture_size| specifies the capturer's video
280 // resolution, but can be empty to mean "unspecified." The first screen
281 // capturer that provides a non-empty |capture_size| will override the value
282 // returned by GetPreferredSize() until all captures have ended.
283 virtual void IncrementCapturerCount(const gfx::Size
& capture_size
) = 0;
284 virtual void DecrementCapturerCount() = 0;
285 virtual int GetCapturerCount() const = 0;
287 // Indicates whether this tab should be considered crashed. The setter will
288 // also notify the delegate when the flag is changed.
289 virtual bool IsCrashed() const = 0;
290 virtual void SetIsCrashed(base::TerminationStatus status
, int error_code
) = 0;
292 virtual base::TerminationStatus
GetCrashedStatus() const = 0;
294 // Whether the tab is in the process of being destroyed.
295 virtual bool IsBeingDestroyed() const = 0;
297 // Convenience method for notifying the delegate of a navigation state
298 // change. See InvalidateType enum.
299 virtual void NotifyNavigationStateChanged(unsigned changed_flags
) = 0;
301 // Get the last time that the WebContents was made active (either when it was
302 // created or shown with WasShown()).
303 virtual base::TimeTicks
GetLastActiveTime() const = 0;
305 // Invoked when the WebContents becomes shown/hidden.
306 virtual void WasShown() = 0;
307 virtual void WasHidden() = 0;
309 // Returns true if the before unload and unload listeners need to be
310 // fired. The value of this changes over time. For example, if true and the
311 // before unload listener is executed and allows the user to exit, then this
313 virtual bool NeedToFireBeforeUnload() = 0;
315 // Runs the beforeunload handler for the main frame. See also ClosePage and
316 // SwapOut in RenderViewHost, which run the unload handler.
318 // |for_cross_site_transition| indicates whether this call is for the current
319 // frame during a cross-process navigation. False means we're closing the
322 // TODO(creis): We should run the beforeunload handler for every frame that
324 virtual void DispatchBeforeUnload(bool for_cross_site_transition
) = 0;
326 // Commands ------------------------------------------------------------------
328 // Stop any pending navigation.
329 virtual void Stop() = 0;
331 // Creates a new WebContents with the same state as this one. The returned
332 // heap-allocated pointer is owned by the caller.
333 virtual WebContents
* Clone() = 0;
335 // Reloads the focused frame.
336 virtual void ReloadFocusedFrame(bool ignore_cache
) = 0;
338 // Editing commands ----------------------------------------------------------
340 virtual void Undo() = 0;
341 virtual void Redo() = 0;
342 virtual void Cut() = 0;
343 virtual void Copy() = 0;
344 virtual void CopyToFindPboard() = 0;
345 virtual void Paste() = 0;
346 virtual void PasteAndMatchStyle() = 0;
347 virtual void Delete() = 0;
348 virtual void SelectAll() = 0;
349 virtual void Unselect() = 0;
351 // Replaces the currently selected word or a word around the cursor.
352 virtual void Replace(const base::string16
& word
) = 0;
354 // Replaces the misspelling in the current selection.
355 virtual void ReplaceMisspelling(const base::string16
& word
) = 0;
357 // Let the renderer know that the menu has been closed.
358 virtual void NotifyContextMenuClosed(
359 const CustomContextMenuContext
& context
) = 0;
361 // Executes custom context menu action that was provided from Blink.
362 virtual void ExecuteCustomContextMenuCommand(
363 int action
, const CustomContextMenuContext
& context
) = 0;
365 // Views and focus -----------------------------------------------------------
367 // Returns the native widget that contains the contents of the tab.
368 virtual gfx::NativeView
GetNativeView() = 0;
370 // Returns the native widget with the main content of the tab (i.e. the main
371 // render view host, though there may be many popups in the tab as children of
373 virtual gfx::NativeView
GetContentNativeView() = 0;
375 // Returns the outermost native view. This will be used as the parent for
377 virtual gfx::NativeWindow
GetTopLevelNativeWindow() = 0;
379 // Computes the rectangle for the native widget that contains the contents of
380 // the tab in the screen coordinate system.
381 virtual gfx::Rect
GetContainerBounds() = 0;
383 // Get the bounds of the View, relative to the parent.
384 virtual gfx::Rect
GetViewBounds() = 0;
386 // Returns the current drop data, if any.
387 virtual DropData
* GetDropData() = 0;
389 // Sets focus to the native widget for this tab.
390 virtual void Focus() = 0;
392 // Sets focus to the appropriate element when the WebContents is shown the
394 virtual void SetInitialFocus() = 0;
396 // Stores the currently focused view.
397 virtual void StoreFocus() = 0;
399 // Restores focus to the last focus view. If StoreFocus has not yet been
400 // invoked, SetInitialFocus is invoked.
401 virtual void RestoreFocus() = 0;
403 // Focuses the first (last if |reverse| is true) element in the page.
404 // Invoked when this tab is getting the focus through tab traversal (|reverse|
405 // is true when using Shift-Tab).
406 virtual void FocusThroughTabTraversal(bool reverse
) = 0;
408 // Interstitials -------------------------------------------------------------
410 // Various other systems need to know about our interstitials.
411 virtual bool ShowingInterstitialPage() const = 0;
413 // Returns the currently showing interstitial, NULL if no interstitial is
415 virtual InterstitialPage
* GetInterstitialPage() const = 0;
417 // Misc state & callbacks ----------------------------------------------------
419 // Check whether we can do the saving page operation this page given its MIME
421 virtual bool IsSavable() = 0;
423 // Prepare for saving the current web page to disk.
424 virtual void OnSavePage() = 0;
426 // Save page with the main HTML file path, the directory for saving resources,
427 // and the save type: HTML only or complete web page. Returns true if the
428 // saving process has been initiated successfully.
429 virtual bool SavePage(const base::FilePath
& main_file
,
430 const base::FilePath
& dir_path
,
431 SavePageType save_type
) = 0;
433 // Saves the given frame's URL to the local filesystem..
434 virtual void SaveFrame(const GURL
& url
,
435 const Referrer
& referrer
) = 0;
437 // Generate an MHTML representation of the current page in the given file.
438 virtual void GenerateMHTML(
439 const base::FilePath
& file
,
440 const base::Callback
<void(
441 int64
/* size of the file */)>& callback
) = 0;
443 // Returns true if the active NavigationEntry's page_id equals page_id.
444 virtual bool IsActiveEntry(int32 page_id
) = 0;
446 // Returns the contents MIME type after a navigation.
447 virtual const std::string
& GetContentsMimeType() const = 0;
449 // Returns true if this WebContents will notify about disconnection.
450 virtual bool WillNotifyDisconnection() const = 0;
452 // Override the encoding and reload the page by sending down
453 // ViewMsg_SetPageEncoding to the renderer. |UpdateEncoding| is kinda
454 // the opposite of this, by which 'browser' is notified of
455 // the encoding of the current tab from 'renderer' (determined by
456 // auto-detect, http header, meta, bom detection, etc).
457 virtual void SetOverrideEncoding(const std::string
& encoding
) = 0;
459 // Remove any user-defined override encoding and reload by sending down
460 // ViewMsg_ResetPageEncodingToDefault to the renderer.
461 virtual void ResetOverrideEncoding() = 0;
463 // Returns the settings which get passed to the renderer.
464 virtual content::RendererPreferences
* GetMutableRendererPrefs() = 0;
466 // Tells the tab to close now. The tab will take care not to close until it's
467 // out of nested message loops.
468 virtual void Close() = 0;
470 // A render view-originated drag has ended. Informs the render view host and
471 // WebContentsDelegate.
472 virtual void SystemDragEnded() = 0;
474 // Notification the user has made a gesture while focus was on the
475 // page. This is used to avoid uninitiated user downloads (aka carpet
476 // bombing), see DownloadRequestLimiter for details.
477 virtual void UserGestureDone() = 0;
479 // Indicates if this tab was explicitly closed by the user (control-w, close
480 // tab menu item...). This is false for actions that indirectly close the tab,
481 // such as closing the window. The setter is maintained by TabStripModel, and
482 // the getter only useful from within TAB_CLOSED notification
483 virtual void SetClosedByUserGesture(bool value
) = 0;
484 virtual bool GetClosedByUserGesture() const = 0;
486 // Gets the zoom level for this tab.
487 virtual double GetZoomLevel() const = 0;
489 // Gets the zoom percent for this tab.
490 virtual int GetZoomPercent(bool* enable_increment
,
491 bool* enable_decrement
) const = 0;
493 // Opens view-source tab for this contents.
494 virtual void ViewSource() = 0;
496 virtual void ViewFrameSource(const GURL
& url
,
497 const PageState
& page_state
)= 0;
499 // Gets the minimum/maximum zoom percent.
500 virtual int GetMinimumZoomPercent() const = 0;
501 virtual int GetMaximumZoomPercent() const = 0;
503 // Gets the preferred size of the contents.
504 virtual gfx::Size
GetPreferredSize() const = 0;
506 // Called when the reponse to a pending mouse lock request has arrived.
507 // Returns true if |allowed| is true and the mouse has been successfully
509 virtual bool GotResponseToLockMouseRequest(bool allowed
) = 0;
511 // Called when the user has selected a color in the color chooser.
512 virtual void DidChooseColorInColorChooser(SkColor color
) = 0;
514 // Called when the color chooser has ended.
515 virtual void DidEndColorChooser() = 0;
517 // Returns true if the location bar should be focused by default rather than
518 // the page contents. The view calls this function when the tab is focused
519 // to see what it should do.
520 virtual bool FocusLocationBarByDefault() = 0;
522 // Does this have an opener associated with it?
523 virtual bool HasOpener() const = 0;
525 typedef base::Callback
<void(
527 int, /* HTTP status code */
528 const GURL
&, /* image_url */
529 const std::vector
<SkBitmap
>&, /* bitmaps */
530 /* The sizes in pixel of the bitmaps before they were resized due to the
531 max bitmap size passed to DownloadImage(). Each entry in the bitmaps
532 vector corresponds to an entry in the sizes vector. If a bitmap was
533 resized, there should be a single returned bitmap. */
534 const std::vector
<gfx::Size
>&)>
535 ImageDownloadCallback
;
537 // Sends a request to download the given image |url| and returns the unique
538 // id of the download request. When the download is finished, |callback| will
539 // be called with the bitmaps received from the renderer. If |is_favicon| is
540 // true, the cookies are not sent and not accepted during download.
541 // Bitmaps with pixel sizes larger than |max_bitmap_size| are filtered out
542 // from the bitmap results. If there are no bitmap results <=
543 // |max_bitmap_size|, the smallest bitmap is resized to |max_bitmap_size| and
544 // is the only result. A |max_bitmap_size| of 0 means unlimited.
545 virtual int DownloadImage(const GURL
& url
,
547 uint32_t max_bitmap_size
,
548 const ImageDownloadCallback
& callback
) = 0;
550 // Returns true if the WebContents is responsible for displaying a subframe
551 // in a different process from its parent page.
552 // TODO: this doesn't really belong here. With site isolation, this should be
553 // removed since we can then embed iframes in different processes.
554 virtual bool IsSubframe() const = 0;
556 // Sets the zoom level for the current page and all BrowserPluginGuests
558 virtual void SetZoomLevel(double level
) = 0;
560 // Finds text on a page.
561 virtual void Find(int request_id
,
562 const base::string16
& search_text
,
563 const blink::WebFindOptions
& options
) = 0;
565 // Notifies the renderer that the user has closed the FindInPage window
566 // (and what action to take regarding the selection).
567 virtual void StopFinding(StopFindAction action
) = 0;
569 // Requests the renderer to insert CSS into the main frame's document.
570 virtual void InsertCSS(const std::string
& css
) = 0;
572 #if defined(OS_ANDROID)
573 CONTENT_EXPORT
static WebContents
* FromJavaWebContents(
574 jobject jweb_contents_android
);
575 virtual base::android::ScopedJavaLocalRef
<jobject
> GetJavaWebContents() = 0;
576 #elif defined(OS_MACOSX)
577 // The web contents view assumes that its view will never be overlapped by
578 // another view (either partially or fully). This allows it to perform
579 // optimizations. If the view is in a view hierarchy where it might be
580 // overlapped by another view, notify the view by calling this with |true|.
581 virtual void SetAllowOverlappingViews(bool overlapping
) = 0;
583 // Returns true if overlapping views are allowed, false otherwise.
584 virtual bool GetAllowOverlappingViews() = 0;
586 // To draw two overlapping web contents view, the underlaying one should
587 // know about the overlaying one. Caller must ensure that |overlay| exists
588 // until |RemoveOverlayView| is called.
589 virtual void SetOverlayView(WebContents
* overlay
,
590 const gfx::Point
& offset
) = 0;
592 // Removes the previously set overlay view.
593 virtual void RemoveOverlayView() = 0;
597 // This interface should only be implemented inside content.
598 friend class WebContentsImpl
;
602 } // namespace content
604 #endif // CONTENT_PUBLIC_BROWSER_WEB_CONTENTS_H_