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/native_widget_types.h"
27 #include "ui/gfx/rect.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 int main_frame_routing_id
;
109 // Initial size of the new WebContent's view. Can be (0, 0) if not needed.
110 gfx::Size initial_size
;
112 // True if the contents should be initially hidden.
113 bool initially_hidden
;
115 // If non-null then this WebContents will be hosted by a BrowserPlugin.
116 BrowserPluginGuestDelegate
* guest_delegate
;
118 // Used to specify the location context which display the new view should
119 // belong. This can be NULL if not needed.
120 gfx::NativeView context
;
123 // Creates a new WebContents.
124 CONTENT_EXPORT
static WebContents
* Create(const CreateParams
& params
);
126 // Similar to Create() above but should be used when you need to prepopulate
127 // the SessionStorageNamespaceMap of the WebContents. This can happen if
128 // you duplicate a WebContents, try to reconstitute it from a saved state,
129 // or when you create a new WebContents based on another one (eg., when
130 // servicing a window.open() call).
132 // You do not want to call this. If you think you do, make sure you completely
133 // understand when SessionStorageNamespace objects should be cloned, why
134 // they should not be shared by multiple WebContents, and what bad things
135 // can happen if you share the object.
136 CONTENT_EXPORT
static WebContents
* CreateWithSessionStorage(
137 const CreateParams
& params
,
138 const SessionStorageNamespaceMap
& session_storage_namespace_map
);
140 // Returns a WebContents that wraps the RenderViewHost, or NULL if the
141 // render view host's delegate isn't a WebContents.
142 CONTENT_EXPORT
static WebContents
* FromRenderViewHost(
143 const RenderViewHost
* rvh
);
145 CONTENT_EXPORT
static WebContents
* FromRenderFrameHost(RenderFrameHost
* rfh
);
147 virtual ~WebContents() {}
149 // Intrinsic tab state -------------------------------------------------------
151 // Gets/Sets the delegate.
152 virtual WebContentsDelegate
* GetDelegate() = 0;
153 virtual void SetDelegate(WebContentsDelegate
* delegate
) = 0;
155 // Gets the controller for this WebContents.
156 virtual NavigationController
& GetController() = 0;
157 virtual const NavigationController
& GetController() const = 0;
159 // Returns the user browser context associated with this WebContents (via the
160 // NavigationController).
161 virtual content::BrowserContext
* GetBrowserContext() const = 0;
163 // Gets the URL that is currently being displayed, if there is one.
164 // This method is deprecated. DO NOT USE! Pick either |GetVisibleURL| or
165 // |GetLastCommittedURL| as appropriate.
166 virtual const GURL
& GetURL() const = 0;
168 // Gets the URL currently being displayed in the URL bar, if there is one.
169 // This URL might be a pending navigation that hasn't committed yet, so it is
170 // not guaranteed to match the current page in this WebContents. A typical
171 // example of this is interstitials, which show the URL of the new/loading
172 // page (active) but the security context is of the old page (last committed).
173 virtual const GURL
& GetVisibleURL() const = 0;
175 // Gets the last committed URL. It represents the current page that is
176 // displayed in this WebContents. It represents the current security
178 virtual const GURL
& GetLastCommittedURL() const = 0;
180 // Return the currently active RenderProcessHost and RenderViewHost. Each of
181 // these may change over time.
182 virtual RenderProcessHost
* GetRenderProcessHost() const = 0;
184 // Returns the main frame for the currently active view.
185 virtual RenderFrameHost
* GetMainFrame() = 0;
187 // Returns the focused frame for the currently active view.
188 virtual RenderFrameHost
* GetFocusedFrame() = 0;
190 // Calls |on_frame| for each frame in the currently active view.
191 virtual void ForEachFrame(
192 const base::Callback
<void(RenderFrameHost
*)>& on_frame
) = 0;
194 // Sends the given IPC to all frames in the currently active view. This is a
195 // convenience method instead of calling ForEach.
196 virtual void SendToAllFrames(IPC::Message
* message
) = 0;
198 // Gets the current RenderViewHost for this tab.
199 virtual RenderViewHost
* GetRenderViewHost() const = 0;
201 // Gets the current RenderViewHost's routing id. Returns
202 // MSG_ROUTING_NONE when there is no RenderViewHost.
203 virtual int GetRoutingID() const = 0;
205 // Returns the currently active RenderWidgetHostView. This may change over
206 // time and can be NULL (during setup and teardown).
207 virtual RenderWidgetHostView
* GetRenderWidgetHostView() const = 0;
209 // Returns the currently active fullscreen widget. If there is none, returns
211 virtual RenderWidgetHostView
* GetFullscreenRenderWidgetHostView() const = 0;
213 // Create a WebUI page for the given url. In most cases, this doesn't need to
214 // be called by embedders since content will create its own WebUI objects as
215 // necessary. However if the embedder wants to create its own WebUI object and
216 // keep track of it manually, it can use this.
217 virtual WebUI
* CreateWebUI(const GURL
& url
) = 0;
219 // Returns the committed WebUI if one exists, otherwise the pending one.
220 virtual WebUI
* GetWebUI() const = 0;
221 virtual WebUI
* GetCommittedWebUI() const = 0;
223 // Allows overriding the user agent used for NavigationEntries it owns.
224 virtual void SetUserAgentOverride(const std::string
& override
) = 0;
225 virtual const std::string
& GetUserAgentOverride() const = 0;
227 // Enable the accessibility tree for this WebContents in the renderer,
228 // but don't enable creating a native accessibility tree on the browser
230 virtual void EnableTreeOnlyAccessibilityMode() = 0;
232 // Returns true only if "tree only" accessibility mode is on.
233 virtual bool IsTreeOnlyAccessibilityModeForTesting() const = 0;
235 // Returns true only if complete accessibility mode is on, meaning there's
236 // both renderer accessibility, and a native browser accessibility tree.
237 virtual bool IsFullAccessibilityModeForTesting() const = 0;
240 virtual void SetParentNativeViewAccessible(
241 gfx::NativeViewAccessible accessible_parent
) = 0;
244 // Tab navigation state ------------------------------------------------------
246 // Returns the current navigation properties, which if a navigation is
247 // pending may be provisional (e.g., the navigation could result in a
248 // download, in which case the URL would revert to what it was previously).
249 virtual const base::string16
& GetTitle() const = 0;
251 // The max page ID for any page that the current SiteInstance has loaded in
252 // this WebContents. Page IDs are specific to a given SiteInstance and
253 // WebContents, corresponding to a specific RenderView in the renderer.
254 // Page IDs increase with each new page that is loaded by a tab.
255 virtual int32
GetMaxPageID() = 0;
257 // The max page ID for any page that the given SiteInstance has loaded in
259 virtual int32
GetMaxPageIDForSiteInstance(SiteInstance
* site_instance
) = 0;
261 // Returns the SiteInstance associated with the current page.
262 virtual SiteInstance
* GetSiteInstance() const = 0;
264 // Returns the SiteInstance for the pending navigation, if any. Otherwise
265 // returns the current SiteInstance.
266 virtual SiteInstance
* GetPendingSiteInstance() const = 0;
268 // Returns whether this WebContents is loading a resource.
269 virtual bool IsLoading() const = 0;
271 // Returns whether this WebContents is loading and and the load is to a
272 // different top-level document (rather than being a navigation within the
273 // same document). This being true implies that IsLoading() is also true.
274 virtual bool IsLoadingToDifferentDocument() const = 0;
276 // Returns whether this WebContents is waiting for a first-response for the
277 // main resource of the page.
278 virtual bool IsWaitingForResponse() const = 0;
280 // Returns the current load state and the URL associated with it.
281 virtual const net::LoadStateWithParam
& GetLoadState() const = 0;
282 virtual const base::string16
& GetLoadStateHost() const = 0;
284 // Returns the upload progress.
285 virtual uint64
GetUploadSize() const = 0;
286 virtual uint64
GetUploadPosition() const = 0;
288 // Returns a set of the site URLs currently committed in this tab.
289 virtual std::set
<GURL
> GetSitesInTab() const = 0;
291 // Returns the character encoding of the page.
292 virtual const std::string
& GetEncoding() const = 0;
294 // True if this is a secure page which displayed insecure content.
295 virtual bool DisplayedInsecureContent() const = 0;
297 // Internal state ------------------------------------------------------------
299 // Indicates whether the WebContents is being captured (e.g., for screenshots
300 // or mirroring). Increment calls must be balanced with an equivalent number
301 // of decrement calls. |capture_size| specifies the capturer's video
302 // resolution, but can be empty to mean "unspecified." The first screen
303 // capturer that provides a non-empty |capture_size| will override the value
304 // returned by GetPreferredSize() until all captures have ended.
305 virtual void IncrementCapturerCount(const gfx::Size
& capture_size
) = 0;
306 virtual void DecrementCapturerCount() = 0;
307 virtual int GetCapturerCount() const = 0;
309 // Indicates/Sets whether all audio output from this WebContents is muted.
310 virtual bool IsAudioMuted() const = 0;
311 virtual void SetAudioMuted(bool mute
) = 0;
313 // Indicates whether this tab should be considered crashed. The setter will
314 // also notify the delegate when the flag is changed.
315 virtual bool IsCrashed() const = 0;
316 virtual void SetIsCrashed(base::TerminationStatus status
, int error_code
) = 0;
318 virtual base::TerminationStatus
GetCrashedStatus() const = 0;
320 // Whether the tab is in the process of being destroyed.
321 virtual bool IsBeingDestroyed() const = 0;
323 // Convenience method for notifying the delegate of a navigation state
325 virtual void NotifyNavigationStateChanged(InvalidateTypes changed_flags
) = 0;
327 // Get the last time that the WebContents was made active (either when it was
328 // created or shown with WasShown()).
329 virtual base::TimeTicks
GetLastActiveTime() const = 0;
331 // Invoked when the WebContents becomes shown/hidden.
332 virtual void WasShown() = 0;
333 virtual void WasHidden() = 0;
335 // Returns true if the before unload and unload listeners need to be
336 // fired. The value of this changes over time. For example, if true and the
337 // before unload listener is executed and allows the user to exit, then this
339 virtual bool NeedToFireBeforeUnload() = 0;
341 // Runs the beforeunload handler for the main frame. See also ClosePage and
342 // SwapOut in RenderViewHost, which run the unload handler.
344 // |for_cross_site_transition| indicates whether this call is for the current
345 // frame during a cross-process navigation. False means we're closing the
348 // TODO(creis): We should run the beforeunload handler for every frame that
350 virtual void DispatchBeforeUnload(bool for_cross_site_transition
) = 0;
352 // Commands ------------------------------------------------------------------
354 // Stop any pending navigation.
355 virtual void Stop() = 0;
357 // Creates a new WebContents with the same state as this one. The returned
358 // heap-allocated pointer is owned by the caller.
359 virtual WebContents
* Clone() = 0;
361 // Reloads the focused frame.
362 virtual void ReloadFocusedFrame(bool ignore_cache
) = 0;
364 // Editing commands ----------------------------------------------------------
366 virtual void Undo() = 0;
367 virtual void Redo() = 0;
368 virtual void Cut() = 0;
369 virtual void Copy() = 0;
370 virtual void CopyToFindPboard() = 0;
371 virtual void Paste() = 0;
372 virtual void PasteAndMatchStyle() = 0;
373 virtual void Delete() = 0;
374 virtual void SelectAll() = 0;
375 virtual void Unselect() = 0;
377 // Replaces the currently selected word or a word around the cursor.
378 virtual void Replace(const base::string16
& word
) = 0;
380 // Replaces the misspelling in the current selection.
381 virtual void ReplaceMisspelling(const base::string16
& word
) = 0;
383 // Let the renderer know that the menu has been closed.
384 virtual void NotifyContextMenuClosed(
385 const CustomContextMenuContext
& context
) = 0;
387 // Executes custom context menu action that was provided from Blink.
388 virtual void ExecuteCustomContextMenuCommand(
389 int action
, const CustomContextMenuContext
& context
) = 0;
391 // Views and focus -----------------------------------------------------------
393 // Returns the native widget that contains the contents of the tab.
394 virtual gfx::NativeView
GetNativeView() = 0;
396 // Returns the native widget with the main content of the tab (i.e. the main
397 // render view host, though there may be many popups in the tab as children of
399 virtual gfx::NativeView
GetContentNativeView() = 0;
401 // Returns the outermost native view. This will be used as the parent for
403 virtual gfx::NativeWindow
GetTopLevelNativeWindow() = 0;
405 // Computes the rectangle for the native widget that contains the contents of
406 // the tab in the screen coordinate system.
407 virtual gfx::Rect
GetContainerBounds() = 0;
409 // Get the bounds of the View, relative to the parent.
410 virtual gfx::Rect
GetViewBounds() = 0;
412 // Returns the current drop data, if any.
413 virtual DropData
* GetDropData() = 0;
415 // Sets focus to the native widget for this tab.
416 virtual void Focus() = 0;
418 // Sets focus to the appropriate element when the WebContents is shown the
420 virtual void SetInitialFocus() = 0;
422 // Stores the currently focused view.
423 virtual void StoreFocus() = 0;
425 // Restores focus to the last focus view. If StoreFocus has not yet been
426 // invoked, SetInitialFocus is invoked.
427 virtual void RestoreFocus() = 0;
429 // Focuses the first (last if |reverse| is true) element in the page.
430 // Invoked when this tab is getting the focus through tab traversal (|reverse|
431 // is true when using Shift-Tab).
432 virtual void FocusThroughTabTraversal(bool reverse
) = 0;
434 // Interstitials -------------------------------------------------------------
436 // Various other systems need to know about our interstitials.
437 virtual bool ShowingInterstitialPage() const = 0;
439 // Returns the currently showing interstitial, NULL if no interstitial is
441 virtual InterstitialPage
* GetInterstitialPage() const = 0;
443 // Misc state & callbacks ----------------------------------------------------
445 // Check whether we can do the saving page operation this page given its MIME
447 virtual bool IsSavable() = 0;
449 // Prepare for saving the current web page to disk.
450 virtual void OnSavePage() = 0;
452 // Save page with the main HTML file path, the directory for saving resources,
453 // and the save type: HTML only or complete web page. Returns true if the
454 // saving process has been initiated successfully.
455 virtual bool SavePage(const base::FilePath
& main_file
,
456 const base::FilePath
& dir_path
,
457 SavePageType save_type
) = 0;
459 // Saves the given frame's URL to the local filesystem..
460 virtual void SaveFrame(const GURL
& url
,
461 const Referrer
& referrer
) = 0;
463 // Generate an MHTML representation of the current page in the given file.
464 virtual void GenerateMHTML(
465 const base::FilePath
& file
,
466 const base::Callback
<void(
467 int64
/* size of the file */)>& callback
) = 0;
469 // Returns the contents MIME type after a navigation.
470 virtual const std::string
& GetContentsMimeType() const = 0;
472 // Returns true if this WebContents will notify about disconnection.
473 virtual bool WillNotifyDisconnection() const = 0;
475 // Override the encoding and reload the page by sending down
476 // ViewMsg_SetPageEncoding to the renderer. |UpdateEncoding| is kinda
477 // the opposite of this, by which 'browser' is notified of
478 // the encoding of the current tab from 'renderer' (determined by
479 // auto-detect, http header, meta, bom detection, etc).
480 virtual void SetOverrideEncoding(const std::string
& encoding
) = 0;
482 // Remove any user-defined override encoding and reload by sending down
483 // ViewMsg_ResetPageEncodingToDefault to the renderer.
484 virtual void ResetOverrideEncoding() = 0;
486 // Returns the settings which get passed to the renderer.
487 virtual content::RendererPreferences
* GetMutableRendererPrefs() = 0;
489 // Tells the tab to close now. The tab will take care not to close until it's
490 // out of nested message loops.
491 virtual void Close() = 0;
493 // A render view-originated drag has ended. Informs the render view host and
494 // WebContentsDelegate.
495 virtual void SystemDragEnded() = 0;
497 // Notification the user has made a gesture while focus was on the
498 // page. This is used to avoid uninitiated user downloads (aka carpet
499 // bombing), see DownloadRequestLimiter for details.
500 virtual void UserGestureDone() = 0;
502 // Indicates if this tab was explicitly closed by the user (control-w, close
503 // tab menu item...). This is false for actions that indirectly close the tab,
504 // such as closing the window. The setter is maintained by TabStripModel, and
505 // the getter only useful from within TAB_CLOSED notification
506 virtual void SetClosedByUserGesture(bool value
) = 0;
507 virtual bool GetClosedByUserGesture() const = 0;
509 // Opens view-source tab for this contents.
510 virtual void ViewSource() = 0;
512 virtual void ViewFrameSource(const GURL
& url
,
513 const PageState
& page_state
)= 0;
515 // Gets the minimum/maximum zoom percent.
516 virtual int GetMinimumZoomPercent() const = 0;
517 virtual int GetMaximumZoomPercent() const = 0;
519 // Gets the preferred size of the contents.
520 virtual gfx::Size
GetPreferredSize() const = 0;
522 // Called when the reponse to a pending mouse lock request has arrived.
523 // Returns true if |allowed| is true and the mouse has been successfully
525 virtual bool GotResponseToLockMouseRequest(bool allowed
) = 0;
527 // Called when the user has selected a color in the color chooser.
528 virtual void DidChooseColorInColorChooser(SkColor color
) = 0;
530 // Called when the color chooser has ended.
531 virtual void DidEndColorChooser() = 0;
533 // Returns true if the location bar should be focused by default rather than
534 // the page contents. The view calls this function when the tab is focused
535 // to see what it should do.
536 virtual bool FocusLocationBarByDefault() = 0;
538 // Does this have an opener associated with it?
539 virtual bool HasOpener() const = 0;
541 typedef base::Callback
<void(
543 int, /* HTTP status code */
544 const GURL
&, /* image_url */
545 const std::vector
<SkBitmap
>&, /* bitmaps */
546 /* The sizes in pixel of the bitmaps before they were resized due to the
547 max bitmap size passed to DownloadImage(). Each entry in the bitmaps
548 vector corresponds to an entry in the sizes vector. If a bitmap was
549 resized, there should be a single returned bitmap. */
550 const std::vector
<gfx::Size
>&)>
551 ImageDownloadCallback
;
553 // Sends a request to download the given image |url| and returns the unique
554 // id of the download request. When the download is finished, |callback| will
555 // be called with the bitmaps received from the renderer. If |is_favicon| is
556 // true, the cookies are not sent and not accepted during download.
557 // Bitmaps with pixel sizes larger than |max_bitmap_size| are filtered out
558 // from the bitmap results. If there are no bitmap results <=
559 // |max_bitmap_size|, the smallest bitmap is resized to |max_bitmap_size| and
560 // is the only result. A |max_bitmap_size| of 0 means unlimited.
561 virtual int DownloadImage(const GURL
& url
,
563 uint32_t max_bitmap_size
,
564 const ImageDownloadCallback
& callback
) = 0;
566 // Returns true if the WebContents is responsible for displaying a subframe
567 // in a different process from its parent page.
568 // TODO: this doesn't really belong here. With site isolation, this should be
569 // removed since we can then embed iframes in different processes.
570 virtual bool IsSubframe() const = 0;
572 // Finds text on a page.
573 virtual void Find(int request_id
,
574 const base::string16
& search_text
,
575 const blink::WebFindOptions
& options
) = 0;
577 // Notifies the renderer that the user has closed the FindInPage window
578 // (and what action to take regarding the selection).
579 virtual void StopFinding(StopFindAction action
) = 0;
581 // Requests the renderer to insert CSS into the main frame's document.
582 virtual void InsertCSS(const std::string
& css
) = 0;
584 // Returns true if audio has recently been audible from the WebContents.
585 virtual bool WasRecentlyAudible() = 0;
587 typedef base::Callback
<void(const Manifest
&)> GetManifestCallback
;
589 // Requests the Manifest of the main frame's document.
590 virtual void GetManifest(const GetManifestCallback
&) = 0;
592 #if defined(OS_ANDROID)
593 CONTENT_EXPORT
static WebContents
* FromJavaWebContents(
594 jobject jweb_contents_android
);
595 virtual base::android::ScopedJavaLocalRef
<jobject
> GetJavaWebContents() = 0;
596 #elif defined(OS_MACOSX)
597 // Allowing other views disables optimizations which assume that only a single
598 // WebContents is present.
599 virtual void SetAllowOtherViews(bool allow
) = 0;
601 // Returns true if other views are allowed, false otherwise.
602 virtual bool GetAllowOtherViews() = 0;
606 // This interface should only be implemented inside content.
607 friend class WebContentsImpl
;
611 } // namespace content
613 #endif // CONTENT_PUBLIC_BROWSER_WEB_CONTENTS_H_