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;
56 class ScreenOrientationDispatcherHost;
58 class WebContentsDelegate;
59 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 virtual ScreenOrientationDispatcherHost* GetScreenOrientationDispatcherHost() = 0;
153 // Gets/Sets the delegate.
154 virtual WebContentsDelegate* GetDelegate() = 0;
155 virtual void SetDelegate(WebContentsDelegate* delegate) = 0;
157 // Gets the controller for this WebContents.
158 virtual NavigationController& GetController() = 0;
159 virtual const NavigationController& GetController() const = 0;
161 // Returns the user browser context associated with this WebContents (via the
162 // NavigationController).
163 virtual content::BrowserContext* GetBrowserContext() const = 0;
165 // Gets the URL that is currently being displayed, if there is one.
166 // This method is deprecated. DO NOT USE! Pick either |GetVisibleURL| or
167 // |GetLastCommittedURL| as appropriate.
168 virtual const GURL& GetURL() const = 0;
170 // Gets the URL currently being displayed in the URL bar, if there is one.
171 // This URL might be a pending navigation that hasn't committed yet, so it is
172 // not guaranteed to match the current page in this WebContents. A typical
173 // example of this is interstitials, which show the URL of the new/loading
174 // page (active) but the security context is of the old page (last committed).
175 virtual const GURL& GetVisibleURL() const = 0;
177 // Gets the last committed URL. It represents the current page that is
178 // displayed in this WebContents. It represents the current security
180 virtual const GURL& GetLastCommittedURL() const = 0;
182 // Return the currently active RenderProcessHost and RenderViewHost. Each of
183 // these may change over time.
184 virtual RenderProcessHost* GetRenderProcessHost() const = 0;
186 // Returns the main frame for the currently active view.
187 virtual RenderFrameHost* GetMainFrame() = 0;
189 // Returns the focused frame for the currently active view.
190 virtual RenderFrameHost* GetFocusedFrame() = 0;
192 // Calls |on_frame| for each frame in the currently active view.
193 virtual void ForEachFrame(
194 const base::Callback<void(RenderFrameHost*)>& on_frame) = 0;
196 // Sends the given IPC to all frames in the currently active view. This is a
197 // convenience method instead of calling ForEach.
198 virtual void SendToAllFrames(IPC::Message* message) = 0;
200 // Gets the current RenderViewHost for this tab.
201 virtual RenderViewHost* GetRenderViewHost() const = 0;
203 // Gets the current RenderViewHost's routing id. Returns
204 // MSG_ROUTING_NONE when there is no RenderViewHost.
205 virtual int GetRoutingID() const = 0;
207 // Returns the currently active RenderWidgetHostView. This may change over
208 // time and can be NULL (during setup and teardown).
209 virtual RenderWidgetHostView* GetRenderWidgetHostView() const = 0;
211 // Returns the currently active fullscreen widget. If there is none, returns
213 virtual RenderWidgetHostView* GetFullscreenRenderWidgetHostView() const = 0;
215 // Create a WebUI page for the given url. In most cases, this doesn't need to
216 // be called by embedders since content will create its own WebUI objects as
217 // necessary. However if the embedder wants to create its own WebUI object and
218 // keep track of it manually, it can use this.
219 virtual WebUI* CreateWebUI(const GURL& url) = 0;
221 // Returns the committed WebUI if one exists, otherwise the pending one.
222 virtual WebUI* GetWebUI() const = 0;
223 virtual WebUI* GetCommittedWebUI() const = 0;
225 // Allows overriding the user agent used for NavigationEntries it owns.
226 virtual void SetUserAgentOverride(const std::string& override) = 0;
227 virtual const std::string& GetUserAgentOverride() const = 0;
229 // Enable the accessibility tree for this WebContents in the renderer,
230 // but don't enable creating a native accessibility tree on the browser
232 virtual void EnableTreeOnlyAccessibilityMode() = 0;
234 // Returns true only if "tree only" accessibility mode is on.
235 virtual bool IsTreeOnlyAccessibilityModeForTesting() const = 0;
237 // Returns true only if complete accessibility mode is on, meaning there's
238 // both renderer accessibility, and a native browser accessibility tree.
239 virtual bool IsFullAccessibilityModeForTesting() const = 0;
242 virtual void SetParentNativeViewAccessible(
243 gfx::NativeViewAccessible accessible_parent) = 0;
246 // Tab navigation state ------------------------------------------------------
248 // Returns the current navigation properties, which if a navigation is
249 // pending may be provisional (e.g., the navigation could result in a
250 // download, in which case the URL would revert to what it was previously).
251 virtual const base::string16& GetTitle() const = 0;
253 // The max page ID for any page that the current SiteInstance has loaded in
254 // this WebContents. Page IDs are specific to a given SiteInstance and
255 // WebContents, corresponding to a specific RenderView in the renderer.
256 // Page IDs increase with each new page that is loaded by a tab.
257 virtual int32 GetMaxPageID() = 0;
259 // The max page ID for any page that the given SiteInstance has loaded in
261 virtual int32 GetMaxPageIDForSiteInstance(SiteInstance* site_instance) = 0;
263 // Returns the SiteInstance associated with the current page.
264 virtual SiteInstance* GetSiteInstance() const = 0;
266 // Returns the SiteInstance for the pending navigation, if any. Otherwise
267 // returns the current SiteInstance.
268 virtual SiteInstance* GetPendingSiteInstance() const = 0;
270 // Returns whether this WebContents is loading a resource.
271 virtual bool IsLoading() const = 0;
273 // Returns whether this WebContents is loading and and the load is to a
274 // different top-level document (rather than being a navigation within the
275 // same document). This being true implies that IsLoading() is also true.
276 virtual bool IsLoadingToDifferentDocument() const = 0;
278 // Returns whether this WebContents is waiting for a first-response for the
279 // main resource of the page.
280 virtual bool IsWaitingForResponse() const = 0;
282 // Returns the current load state and the URL associated with it.
283 virtual const net::LoadStateWithParam& GetLoadState() const = 0;
284 virtual const base::string16& GetLoadStateHost() const = 0;
286 // Returns the upload progress.
287 virtual uint64 GetUploadSize() const = 0;
288 virtual uint64 GetUploadPosition() const = 0;
290 // Returns a set of the site URLs currently committed in this tab.
291 virtual std::set<GURL> GetSitesInTab() const = 0;
293 // Returns the character encoding of the page.
294 virtual const std::string& GetEncoding() const = 0;
296 // True if this is a secure page which displayed insecure content.
297 virtual bool DisplayedInsecureContent() const = 0;
299 // Internal state ------------------------------------------------------------
301 // Indicates whether the WebContents is being captured (e.g., for screenshots
302 // or mirroring). Increment calls must be balanced with an equivalent number
303 // of decrement calls. |capture_size| specifies the capturer's video
304 // resolution, but can be empty to mean "unspecified." The first screen
305 // capturer that provides a non-empty |capture_size| will override the value
306 // returned by GetPreferredSize() until all captures have ended.
307 virtual void IncrementCapturerCount(const gfx::Size& capture_size) = 0;
308 virtual void DecrementCapturerCount() = 0;
309 virtual int GetCapturerCount() const = 0;
311 // Indicates whether this tab should be considered crashed. The setter will
312 // also notify the delegate when the flag is changed.
313 virtual bool IsCrashed() const = 0;
314 virtual void SetIsCrashed(base::TerminationStatus status, int error_code) = 0;
316 virtual base::TerminationStatus GetCrashedStatus() const = 0;
318 // Whether the tab is in the process of being destroyed.
319 virtual bool IsBeingDestroyed() const = 0;
321 // Convenience method for notifying the delegate of a navigation state
323 virtual void NotifyNavigationStateChanged(InvalidateTypes changed_flags) = 0;
325 // Get the last time that the WebContents was made active (either when it was
326 // created or shown with WasShown()).
327 virtual base::TimeTicks GetLastActiveTime() const = 0;
329 // Invoked when the WebContents becomes shown/hidden.
330 virtual void WasShown() = 0;
331 virtual void WasHidden() = 0;
333 // Returns true if the before unload and unload listeners need to be
334 // fired. The value of this changes over time. For example, if true and the
335 // before unload listener is executed and allows the user to exit, then this
337 virtual bool NeedToFireBeforeUnload() = 0;
339 // Runs the beforeunload handler for the main frame. See also ClosePage and
340 // SwapOut in RenderViewHost, which run the unload handler.
342 // |for_cross_site_transition| indicates whether this call is for the current
343 // frame during a cross-process navigation. False means we're closing the
346 // TODO(creis): We should run the beforeunload handler for every frame that
348 virtual void DispatchBeforeUnload(bool for_cross_site_transition) = 0;
350 // Commands ------------------------------------------------------------------
352 // Stop any pending navigation.
353 virtual void Stop() = 0;
355 // Creates a new WebContents with the same state as this one. The returned
356 // heap-allocated pointer is owned by the caller.
357 virtual WebContents* Clone() = 0;
359 // Reloads the focused frame.
360 virtual void ReloadFocusedFrame(bool ignore_cache) = 0;
362 // Editing commands ----------------------------------------------------------
364 virtual void Undo() = 0;
365 virtual void Redo() = 0;
366 virtual void Cut() = 0;
367 virtual void Copy() = 0;
368 virtual void CopyToFindPboard() = 0;
369 virtual void Paste() = 0;
370 virtual void PasteAndMatchStyle() = 0;
371 virtual void Delete() = 0;
372 virtual void SelectAll() = 0;
373 virtual void Unselect() = 0;
375 // Replaces the currently selected word or a word around the cursor.
376 virtual void Replace(const base::string16& word) = 0;
378 // Replaces the misspelling in the current selection.
379 virtual void ReplaceMisspelling(const base::string16& word) = 0;
381 // Let the renderer know that the menu has been closed.
382 virtual void NotifyContextMenuClosed(
383 const CustomContextMenuContext& context) = 0;
385 // Executes custom context menu action that was provided from Blink.
386 virtual void ExecuteCustomContextMenuCommand(
387 int action, const CustomContextMenuContext& context) = 0;
389 // Views and focus -----------------------------------------------------------
391 // Returns the native widget that contains the contents of the tab.
392 virtual gfx::NativeView GetNativeView() = 0;
394 // Returns the native widget with the main content of the tab (i.e. the main
395 // render view host, though there may be many popups in the tab as children of
397 virtual gfx::NativeView GetContentNativeView() = 0;
399 // Returns the outermost native view. This will be used as the parent for
401 virtual gfx::NativeWindow GetTopLevelNativeWindow() = 0;
403 // Computes the rectangle for the native widget that contains the contents of
404 // the tab in the screen coordinate system.
405 virtual gfx::Rect GetContainerBounds() = 0;
407 // Get the bounds of the View, relative to the parent.
408 virtual gfx::Rect GetViewBounds() = 0;
410 // Returns the current drop data, if any.
411 virtual DropData* GetDropData() = 0;
413 // Sets focus to the native widget for this tab.
414 virtual void Focus() = 0;
416 // Sets focus to the appropriate element when the WebContents is shown the
418 virtual void SetInitialFocus() = 0;
420 // Stores the currently focused view.
421 virtual void StoreFocus() = 0;
423 // Restores focus to the last focus view. If StoreFocus has not yet been
424 // invoked, SetInitialFocus is invoked.
425 virtual void RestoreFocus() = 0;
427 // Focuses the first (last if |reverse| is true) element in the page.
428 // Invoked when this tab is getting the focus through tab traversal (|reverse|
429 // is true when using Shift-Tab).
430 virtual void FocusThroughTabTraversal(bool reverse) = 0;
432 // Interstitials -------------------------------------------------------------
434 // Various other systems need to know about our interstitials.
435 virtual bool ShowingInterstitialPage() const = 0;
437 // Returns the currently showing interstitial, NULL if no interstitial is
439 virtual InterstitialPage* GetInterstitialPage() const = 0;
441 // Misc state & callbacks ----------------------------------------------------
443 // Check whether we can do the saving page operation this page given its MIME
445 virtual bool IsSavable() = 0;
447 // Prepare for saving the current web page to disk.
448 virtual void OnSavePage() = 0;
450 // Save page with the main HTML file path, the directory for saving resources,
451 // and the save type: HTML only or complete web page. Returns true if the
452 // saving process has been initiated successfully.
453 virtual bool SavePage(const base::FilePath& main_file,
454 const base::FilePath& dir_path,
455 SavePageType save_type) = 0;
457 // Saves the given frame's URL to the local filesystem..
458 virtual void SaveFrame(const GURL& url,
459 const Referrer& referrer) = 0;
461 // Generate an MHTML representation of the current page in the given file.
462 virtual void GenerateMHTML(
463 const base::FilePath& file,
464 const base::Callback<void(
465 int64 /* size of the file */)>& callback) = 0;
467 // Returns the contents MIME type after a navigation.
468 virtual const std::string& GetContentsMimeType() const = 0;
470 // Returns true if this WebContents will notify about disconnection.
471 virtual bool WillNotifyDisconnection() const = 0;
473 // Override the encoding and reload the page by sending down
474 // ViewMsg_SetPageEncoding to the renderer. |UpdateEncoding| is kinda
475 // the opposite of this, by which 'browser' is notified of
476 // the encoding of the current tab from 'renderer' (determined by
477 // auto-detect, http header, meta, bom detection, etc).
478 virtual void SetOverrideEncoding(const std::string& encoding) = 0;
480 // Remove any user-defined override encoding and reload by sending down
481 // ViewMsg_ResetPageEncodingToDefault to the renderer.
482 virtual void ResetOverrideEncoding() = 0;
484 // Returns the settings which get passed to the renderer.
485 virtual content::RendererPreferences* GetMutableRendererPrefs() = 0;
487 // Tells the tab to close now. The tab will take care not to close until it's
488 // out of nested message loops.
489 virtual void Close() = 0;
491 // A render view-originated drag has ended. Informs the render view host and
492 // WebContentsDelegate.
493 virtual void SystemDragEnded() = 0;
495 // Notification the user has made a gesture while focus was on the
496 // page. This is used to avoid uninitiated user downloads (aka carpet
497 // bombing), see DownloadRequestLimiter for details.
498 virtual void UserGestureDone() = 0;
500 // Indicates if this tab was explicitly closed by the user (control-w, close
501 // tab menu item...). This is false for actions that indirectly close the tab,
502 // such as closing the window. The setter is maintained by TabStripModel, and
503 // the getter only useful from within TAB_CLOSED notification
504 virtual void SetClosedByUserGesture(bool value) = 0;
505 virtual bool GetClosedByUserGesture() const = 0;
507 // Opens view-source tab for this contents.
508 virtual void ViewSource() = 0;
510 virtual void ViewFrameSource(const GURL& url,
511 const PageState& page_state)= 0;
513 // Gets the minimum/maximum zoom percent.
514 virtual int GetMinimumZoomPercent() const = 0;
515 virtual int GetMaximumZoomPercent() const = 0;
517 // Gets the preferred size of the contents.
518 virtual gfx::Size GetPreferredSize() const = 0;
520 // Called when the reponse to a pending mouse lock request has arrived.
521 // Returns true if |allowed| is true and the mouse has been successfully
523 virtual bool GotResponseToLockMouseRequest(bool allowed) = 0;
525 // Called when the user has selected a color in the color chooser.
526 virtual void DidChooseColorInColorChooser(SkColor color) = 0;
528 // Called when the color chooser has ended.
529 virtual void DidEndColorChooser() = 0;
531 // Returns true if the location bar should be focused by default rather than
532 // the page contents. The view calls this function when the tab is focused
533 // to see what it should do.
534 virtual bool FocusLocationBarByDefault() = 0;
536 // Does this have an opener associated with it?
537 virtual bool HasOpener() const = 0;
539 typedef base::Callback<void(
541 int, /* HTTP status code */
542 const GURL&, /* image_url */
543 const std::vector<SkBitmap>&, /* bitmaps */
544 /* The sizes in pixel of the bitmaps before they were resized due to the
545 max bitmap size passed to DownloadImage(). Each entry in the bitmaps
546 vector corresponds to an entry in the sizes vector. If a bitmap was
547 resized, there should be a single returned bitmap. */
548 const std::vector<gfx::Size>&)>
549 ImageDownloadCallback;
551 // Sends a request to download the given image |url| and returns the unique
552 // id of the download request. When the download is finished, |callback| will
553 // be called with the bitmaps received from the renderer. If |is_favicon| is
554 // true, the cookies are not sent and not accepted during download.
555 // Bitmaps with pixel sizes larger than |max_bitmap_size| are filtered out
556 // from the bitmap results. If there are no bitmap results <=
557 // |max_bitmap_size|, the smallest bitmap is resized to |max_bitmap_size| and
558 // is the only result. A |max_bitmap_size| of 0 means unlimited.
559 virtual int DownloadImage(const GURL& url,
561 uint32_t max_bitmap_size,
562 const ImageDownloadCallback& callback) = 0;
564 // Returns true if the WebContents is responsible for displaying a subframe
565 // in a different process from its parent page.
566 // TODO: this doesn't really belong here. With site isolation, this should be
567 // removed since we can then embed iframes in different processes.
568 virtual bool IsSubframe() const = 0;
570 // Finds text on a page.
571 virtual void Find(int request_id,
572 const base::string16& search_text,
573 const blink::WebFindOptions& options) = 0;
575 // Notifies the renderer that the user has closed the FindInPage window
576 // (and what action to take regarding the selection).
577 virtual void StopFinding(StopFindAction action) = 0;
579 // Requests the renderer to insert CSS into the main frame's document.
580 virtual void InsertCSS(const std::string& css) = 0;
582 #if defined(OS_ANDROID)
583 CONTENT_EXPORT static WebContents* FromJavaWebContents(
584 jobject jweb_contents_android);
585 virtual base::android::ScopedJavaLocalRef<jobject> GetJavaWebContents() = 0;
586 #elif defined(OS_MACOSX)
587 // The web contents view assumes that its view will never be overlapped by
588 // another view (either partially or fully). This allows it to perform
589 // optimizations. If the view is in a view hierarchy where it might be
590 // overlapped by another view, notify the view by calling this with |true|.
591 virtual void SetAllowOverlappingViews(bool overlapping) = 0;
593 // Returns true if overlapping views are allowed, false otherwise.
594 virtual bool GetAllowOverlappingViews() = 0;
596 // Allowing other views disables optimizations which assume that only a single
597 // WebContents is present.
598 virtual void SetAllowOtherViews(bool allow) = 0;
600 // Returns true if other views are allowed, false otherwise.
601 virtual bool GetAllowOtherViews() = 0;
605 // This interface should only be implemented inside content.
606 friend class WebContentsImpl;
610 } // namespace content
612 #endif // CONTENT_PUBLIC_BROWSER_WEB_CONTENTS_H_