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;
62 struct RendererPreferences;
64 // WebContents is the core class in content/. A WebContents renders web content
65 // (usually HTML) in a rectangular area.
67 // Instantiating one is simple:
68 // scoped_ptr<content::WebContents> web_contents(
69 // content::WebContents::Create(
70 // content::WebContents::CreateParams(browser_context)));
71 // gfx::NativeView view = web_contents->GetNativeView();
72 // // |view| is an HWND, NSView*, GtkWidget*, etc.; insert it into the view
73 // // hierarchy wherever it needs to go.
75 // That's it; go to your kitchen, grab a scone, and chill. WebContents will do
76 // all the multi-process stuff behind the scenes. More details are at
77 // http://www.chromium.org/developers/design-documents/multi-process-architecture .
79 // Each WebContents has exactly one NavigationController; each
80 // NavigationController belongs to one WebContents. The NavigationController can
81 // be obtained from GetController(), and is used to load URLs into the
82 // WebContents, navigate it backwards/forwards, etc. See navigation_controller.h
84 class WebContents : public PageNavigator,
86 public base::SupportsUserData {
88 struct CONTENT_EXPORT CreateParams {
89 explicit CreateParams(BrowserContext* context);
91 CreateParams(BrowserContext* context, SiteInstance* site);
93 BrowserContext* browser_context;
95 // Specifying a SiteInstance here is optional. It can be set to avoid an
96 // extra process swap if the first navigation is expected to require a
97 // privileged process.
98 SiteInstance* site_instance;
100 // The opener WebContents is the WebContents that initiated this request,
104 // If the opener is suppressed, then the new WebContents doesn't hold a
105 // reference to its opener.
106 bool opener_suppressed;
108 int main_frame_routing_id;
110 // Initial size of the new WebContent's view. Can be (0, 0) if not needed.
111 gfx::Size initial_size;
113 // True if the contents should be initially hidden.
114 bool initially_hidden;
116 // If non-null then this WebContents will be hosted by a BrowserPlugin.
117 BrowserPluginGuestDelegate* guest_delegate;
119 // Used to specify the location context which display the new view should
120 // belong. This can be NULL if not needed.
121 gfx::NativeView context;
124 // Creates a new WebContents.
125 CONTENT_EXPORT static WebContents* Create(const CreateParams& params);
127 // Similar to Create() above but should be used when you need to prepopulate
128 // the SessionStorageNamespaceMap of the WebContents. This can happen if
129 // you duplicate a WebContents, try to reconstitute it from a saved state,
130 // or when you create a new WebContents based on another one (eg., when
131 // servicing a window.open() call).
133 // You do not want to call this. If you think you do, make sure you completely
134 // understand when SessionStorageNamespace objects should be cloned, why
135 // they should not be shared by multiple WebContents, and what bad things
136 // can happen if you share the object.
137 CONTENT_EXPORT static WebContents* CreateWithSessionStorage(
138 const CreateParams& params,
139 const SessionStorageNamespaceMap& session_storage_namespace_map);
141 // Returns a WebContents that wraps the RenderViewHost, or NULL if the
142 // render view host's delegate isn't a WebContents.
143 CONTENT_EXPORT static WebContents* FromRenderViewHost(
144 const RenderViewHost* rvh);
146 CONTENT_EXPORT static WebContents* FromRenderFrameHost(RenderFrameHost* rfh);
148 virtual ~WebContents() {}
150 // Intrinsic tab state -------------------------------------------------------
152 virtual ScreenOrientationDispatcherHost* GetScreenOrientationDispatcherHost() = 0;
154 // Gets/Sets the delegate.
155 virtual WebContentsDelegate* GetDelegate() = 0;
156 virtual void SetDelegate(WebContentsDelegate* delegate) = 0;
158 // Gets the controller for this WebContents.
159 virtual NavigationController& GetController() = 0;
160 virtual const NavigationController& GetController() const = 0;
162 // Returns the user browser context associated with this WebContents (via the
163 // NavigationController).
164 virtual content::BrowserContext* GetBrowserContext() const = 0;
166 // Gets the URL that is currently being displayed, if there is one.
167 // This method is deprecated. DO NOT USE! Pick either |GetVisibleURL| or
168 // |GetLastCommittedURL| as appropriate.
169 virtual const GURL& GetURL() const = 0;
171 // Gets the URL currently being displayed in the URL bar, if there is one.
172 // This URL might be a pending navigation that hasn't committed yet, so it is
173 // not guaranteed to match the current page in this WebContents. A typical
174 // example of this is interstitials, which show the URL of the new/loading
175 // page (active) but the security context is of the old page (last committed).
176 virtual const GURL& GetVisibleURL() const = 0;
178 // Gets the last committed URL. It represents the current page that is
179 // displayed in this WebContents. It represents the current security
181 virtual const GURL& GetLastCommittedURL() const = 0;
183 // Return the currently active RenderProcessHost and RenderViewHost. Each of
184 // these may change over time.
185 virtual RenderProcessHost* GetRenderProcessHost() const = 0;
187 // Returns the main frame for the currently active view.
188 virtual RenderFrameHost* GetMainFrame() = 0;
190 // Returns the focused frame for the currently active view.
191 virtual RenderFrameHost* GetFocusedFrame() = 0;
193 // Calls |on_frame| for each frame in the currently active view.
194 virtual void ForEachFrame(
195 const base::Callback<void(RenderFrameHost*)>& on_frame) = 0;
197 // Sends the given IPC to all frames in the currently active view. This is a
198 // convenience method instead of calling ForEach.
199 virtual void SendToAllFrames(IPC::Message* message) = 0;
201 // Gets the current RenderViewHost for this tab.
202 virtual RenderViewHost* GetRenderViewHost() const = 0;
204 // Gets the current RenderViewHost's routing id. Returns
205 // MSG_ROUTING_NONE when there is no RenderViewHost.
206 virtual int GetRoutingID() const = 0;
208 // Returns the currently active RenderWidgetHostView. This may change over
209 // time and can be NULL (during setup and teardown).
210 virtual RenderWidgetHostView* GetRenderWidgetHostView() const = 0;
212 // Returns the currently active fullscreen widget. If there is none, returns
214 virtual RenderWidgetHostView* GetFullscreenRenderWidgetHostView() const = 0;
216 // Create a WebUI page for the given url. In most cases, this doesn't need to
217 // be called by embedders since content will create its own WebUI objects as
218 // necessary. However if the embedder wants to create its own WebUI object and
219 // keep track of it manually, it can use this.
220 virtual WebUI* CreateWebUI(const GURL& url) = 0;
222 // Returns the committed WebUI if one exists, otherwise the pending one.
223 virtual WebUI* GetWebUI() const = 0;
224 virtual WebUI* GetCommittedWebUI() const = 0;
226 // Allows overriding the user agent used for NavigationEntries it owns.
227 virtual void SetUserAgentOverride(const std::string& override) = 0;
228 virtual const std::string& GetUserAgentOverride() const = 0;
230 // Enable the accessibility tree for this WebContents in the renderer,
231 // but don't enable creating a native accessibility tree on the browser
233 virtual void EnableTreeOnlyAccessibilityMode() = 0;
235 // Returns true only if "tree only" accessibility mode is on.
236 virtual bool IsTreeOnlyAccessibilityModeForTesting() const = 0;
238 // Returns true only if complete accessibility mode is on, meaning there's
239 // both renderer accessibility, and a native browser accessibility tree.
240 virtual bool IsFullAccessibilityModeForTesting() const = 0;
243 virtual void SetParentNativeViewAccessible(
244 gfx::NativeViewAccessible accessible_parent) = 0;
247 // Tab navigation state ------------------------------------------------------
249 // Returns the current navigation properties, which if a navigation is
250 // pending may be provisional (e.g., the navigation could result in a
251 // download, in which case the URL would revert to what it was previously).
252 virtual const base::string16& GetTitle() const = 0;
254 // The max page ID for any page that the current SiteInstance has loaded in
255 // this WebContents. Page IDs are specific to a given SiteInstance and
256 // WebContents, corresponding to a specific RenderView in the renderer.
257 // Page IDs increase with each new page that is loaded by a tab.
258 virtual int32 GetMaxPageID() = 0;
260 // The max page ID for any page that the given SiteInstance has loaded in
262 virtual int32 GetMaxPageIDForSiteInstance(SiteInstance* site_instance) = 0;
264 // Returns the SiteInstance associated with the current page.
265 virtual SiteInstance* GetSiteInstance() const = 0;
267 // Returns the SiteInstance for the pending navigation, if any. Otherwise
268 // returns the current SiteInstance.
269 virtual SiteInstance* GetPendingSiteInstance() const = 0;
271 // Returns whether this WebContents is loading a resource.
272 virtual bool IsLoading() const = 0;
274 // Returns whether this WebContents is loading and and the load is to a
275 // different top-level document (rather than being a navigation within the
276 // same document). This being true implies that IsLoading() is also true.
277 virtual bool IsLoadingToDifferentDocument() const = 0;
279 // Returns whether this WebContents is waiting for a first-response for the
280 // main resource of the page.
281 virtual bool IsWaitingForResponse() const = 0;
283 // Returns the current load state and the URL associated with it.
284 virtual const net::LoadStateWithParam& GetLoadState() const = 0;
285 virtual const base::string16& GetLoadStateHost() const = 0;
287 // Returns the upload progress.
288 virtual uint64 GetUploadSize() const = 0;
289 virtual uint64 GetUploadPosition() const = 0;
291 // Returns a set of the site URLs currently committed in this tab.
292 virtual std::set<GURL> GetSitesInTab() const = 0;
294 // Returns the character encoding of the page.
295 virtual const std::string& GetEncoding() const = 0;
297 // True if this is a secure page which displayed insecure content.
298 virtual bool DisplayedInsecureContent() const = 0;
300 // Internal state ------------------------------------------------------------
302 // Indicates whether the WebContents is being captured (e.g., for screenshots
303 // or mirroring). Increment calls must be balanced with an equivalent number
304 // of decrement calls. |capture_size| specifies the capturer's video
305 // resolution, but can be empty to mean "unspecified." The first screen
306 // capturer that provides a non-empty |capture_size| will override the value
307 // returned by GetPreferredSize() until all captures have ended.
308 virtual void IncrementCapturerCount(const gfx::Size& capture_size) = 0;
309 virtual void DecrementCapturerCount() = 0;
310 virtual int GetCapturerCount() const = 0;
312 // Indicates/Sets whether all audio output from this WebContents is muted.
313 virtual bool IsAudioMuted() const = 0;
314 virtual void SetAudioMuted(bool mute) = 0;
316 // Indicates whether this tab should be considered crashed. The setter will
317 // also notify the delegate when the flag is changed.
318 virtual bool IsCrashed() const = 0;
319 virtual void SetIsCrashed(base::TerminationStatus status, int error_code) = 0;
321 virtual base::TerminationStatus GetCrashedStatus() const = 0;
323 // Whether the tab is in the process of being destroyed.
324 virtual bool IsBeingDestroyed() const = 0;
326 // Convenience method for notifying the delegate of a navigation state
328 virtual void NotifyNavigationStateChanged(InvalidateTypes changed_flags) = 0;
330 // Get the last time that the WebContents was made active (either when it was
331 // created or shown with WasShown()).
332 virtual base::TimeTicks GetLastActiveTime() const = 0;
334 // Invoked when the WebContents becomes shown/hidden.
335 virtual void WasShown() = 0;
336 virtual void WasHidden() = 0;
338 // Returns true if the before unload and unload listeners need to be
339 // fired. The value of this changes over time. For example, if true and the
340 // before unload listener is executed and allows the user to exit, then this
342 virtual bool NeedToFireBeforeUnload() = 0;
344 // Runs the beforeunload handler for the main frame. See also ClosePage and
345 // SwapOut in RenderViewHost, which run the unload handler.
347 // |for_cross_site_transition| indicates whether this call is for the current
348 // frame during a cross-process navigation. False means we're closing the
351 // TODO(creis): We should run the beforeunload handler for every frame that
353 virtual void DispatchBeforeUnload(bool for_cross_site_transition) = 0;
355 // Commands ------------------------------------------------------------------
357 // Stop any pending navigation.
358 virtual void Stop() = 0;
360 // Creates a new WebContents with the same state as this one. The returned
361 // heap-allocated pointer is owned by the caller.
362 virtual WebContents* Clone() = 0;
364 // Reloads the focused frame.
365 virtual void ReloadFocusedFrame(bool ignore_cache) = 0;
367 // Editing commands ----------------------------------------------------------
369 virtual void Undo() = 0;
370 virtual void Redo() = 0;
371 virtual void Cut() = 0;
372 virtual void Copy() = 0;
373 virtual void CopyToFindPboard() = 0;
374 virtual void Paste() = 0;
375 virtual void PasteAndMatchStyle() = 0;
376 virtual void Delete() = 0;
377 virtual void SelectAll() = 0;
378 virtual void Unselect() = 0;
380 // Replaces the currently selected word or a word around the cursor.
381 virtual void Replace(const base::string16& word) = 0;
383 // Replaces the misspelling in the current selection.
384 virtual void ReplaceMisspelling(const base::string16& word) = 0;
386 // Let the renderer know that the menu has been closed.
387 virtual void NotifyContextMenuClosed(
388 const CustomContextMenuContext& context) = 0;
390 // Executes custom context menu action that was provided from Blink.
391 virtual void ExecuteCustomContextMenuCommand(
392 int action, const CustomContextMenuContext& context) = 0;
394 // Views and focus -----------------------------------------------------------
396 // Returns the native widget that contains the contents of the tab.
397 virtual gfx::NativeView GetNativeView() = 0;
399 // Returns the native widget with the main content of the tab (i.e. the main
400 // render view host, though there may be many popups in the tab as children of
402 virtual gfx::NativeView GetContentNativeView() = 0;
404 // Returns the outermost native view. This will be used as the parent for
406 virtual gfx::NativeWindow GetTopLevelNativeWindow() = 0;
408 // Computes the rectangle for the native widget that contains the contents of
409 // the tab in the screen coordinate system.
410 virtual gfx::Rect GetContainerBounds() = 0;
412 // Get the bounds of the View, relative to the parent.
413 virtual gfx::Rect GetViewBounds() = 0;
415 // Returns the current drop data, if any.
416 virtual DropData* GetDropData() = 0;
418 // Sets focus to the native widget for this tab.
419 virtual void Focus() = 0;
421 // Sets focus to the appropriate element when the WebContents is shown the
423 virtual void SetInitialFocus() = 0;
425 // Stores the currently focused view.
426 virtual void StoreFocus() = 0;
428 // Restores focus to the last focus view. If StoreFocus has not yet been
429 // invoked, SetInitialFocus is invoked.
430 virtual void RestoreFocus() = 0;
432 // Focuses the first (last if |reverse| is true) element in the page.
433 // Invoked when this tab is getting the focus through tab traversal (|reverse|
434 // is true when using Shift-Tab).
435 virtual void FocusThroughTabTraversal(bool reverse) = 0;
437 // Interstitials -------------------------------------------------------------
439 // Various other systems need to know about our interstitials.
440 virtual bool ShowingInterstitialPage() const = 0;
442 // Returns the currently showing interstitial, NULL if no interstitial is
444 virtual InterstitialPage* GetInterstitialPage() const = 0;
446 // Misc state & callbacks ----------------------------------------------------
448 // Check whether we can do the saving page operation this page given its MIME
450 virtual bool IsSavable() = 0;
452 // Prepare for saving the current web page to disk.
453 virtual void OnSavePage() = 0;
455 // Save page with the main HTML file path, the directory for saving resources,
456 // and the save type: HTML only or complete web page. Returns true if the
457 // saving process has been initiated successfully.
458 virtual bool SavePage(const base::FilePath& main_file,
459 const base::FilePath& dir_path,
460 SavePageType save_type) = 0;
462 // Saves the given frame's URL to the local filesystem..
463 virtual void SaveFrame(const GURL& url,
464 const Referrer& referrer) = 0;
466 // Generate an MHTML representation of the current page in the given file.
467 virtual void GenerateMHTML(
468 const base::FilePath& file,
469 const base::Callback<void(
470 int64 /* size of the file */)>& callback) = 0;
472 // Returns the contents MIME type after a navigation.
473 virtual const std::string& GetContentsMimeType() const = 0;
475 // Returns true if this WebContents will notify about disconnection.
476 virtual bool WillNotifyDisconnection() const = 0;
478 // Override the encoding and reload the page by sending down
479 // ViewMsg_SetPageEncoding to the renderer. |UpdateEncoding| is kinda
480 // the opposite of this, by which 'browser' is notified of
481 // the encoding of the current tab from 'renderer' (determined by
482 // auto-detect, http header, meta, bom detection, etc).
483 virtual void SetOverrideEncoding(const std::string& encoding) = 0;
485 // Remove any user-defined override encoding and reload by sending down
486 // ViewMsg_ResetPageEncodingToDefault to the renderer.
487 virtual void ResetOverrideEncoding() = 0;
489 // Returns the settings which get passed to the renderer.
490 virtual content::RendererPreferences* GetMutableRendererPrefs() = 0;
492 // Tells the tab to close now. The tab will take care not to close until it's
493 // out of nested message loops.
494 virtual void Close() = 0;
496 // A render view-originated drag has ended. Informs the render view host and
497 // WebContentsDelegate.
498 virtual void SystemDragEnded() = 0;
500 // Notification the user has made a gesture while focus was on the
501 // page. This is used to avoid uninitiated user downloads (aka carpet
502 // bombing), see DownloadRequestLimiter for details.
503 virtual void UserGestureDone() = 0;
505 // Indicates if this tab was explicitly closed by the user (control-w, close
506 // tab menu item...). This is false for actions that indirectly close the tab,
507 // such as closing the window. The setter is maintained by TabStripModel, and
508 // the getter only useful from within TAB_CLOSED notification
509 virtual void SetClosedByUserGesture(bool value) = 0;
510 virtual bool GetClosedByUserGesture() const = 0;
512 // Opens view-source tab for this contents.
513 virtual void ViewSource() = 0;
515 virtual void ViewFrameSource(const GURL& url,
516 const PageState& page_state)= 0;
518 // Gets the minimum/maximum zoom percent.
519 virtual int GetMinimumZoomPercent() const = 0;
520 virtual int GetMaximumZoomPercent() const = 0;
522 // Gets the preferred size of the contents.
523 virtual gfx::Size GetPreferredSize() const = 0;
525 // Called when the reponse to a pending mouse lock request has arrived.
526 // Returns true if |allowed| is true and the mouse has been successfully
528 virtual bool GotResponseToLockMouseRequest(bool allowed) = 0;
530 // Called when the user has selected a color in the color chooser.
531 virtual void DidChooseColorInColorChooser(SkColor color) = 0;
533 // Called when the color chooser has ended.
534 virtual void DidEndColorChooser() = 0;
536 // Returns true if the location bar should be focused by default rather than
537 // the page contents. The view calls this function when the tab is focused
538 // to see what it should do.
539 virtual bool FocusLocationBarByDefault() = 0;
541 // Does this have an opener associated with it?
542 virtual bool HasOpener() const = 0;
544 typedef base::Callback<void(
546 int, /* HTTP status code */
547 const GURL&, /* image_url */
548 const std::vector<SkBitmap>&, /* bitmaps */
549 /* The sizes in pixel of the bitmaps before they were resized due to the
550 max bitmap size passed to DownloadImage(). Each entry in the bitmaps
551 vector corresponds to an entry in the sizes vector. If a bitmap was
552 resized, there should be a single returned bitmap. */
553 const std::vector<gfx::Size>&)>
554 ImageDownloadCallback;
556 // Sends a request to download the given image |url| and returns the unique
557 // id of the download request. When the download is finished, |callback| will
558 // be called with the bitmaps received from the renderer. If |is_favicon| is
559 // true, the cookies are not sent and not accepted during download.
560 // Bitmaps with pixel sizes larger than |max_bitmap_size| are filtered out
561 // from the bitmap results. If there are no bitmap results <=
562 // |max_bitmap_size|, the smallest bitmap is resized to |max_bitmap_size| and
563 // is the only result. A |max_bitmap_size| of 0 means unlimited.
564 virtual int DownloadImage(const GURL& url,
566 uint32_t max_bitmap_size,
567 const ImageDownloadCallback& callback) = 0;
569 // Returns true if the WebContents is responsible for displaying a subframe
570 // in a different process from its parent page.
571 // TODO: this doesn't really belong here. With site isolation, this should be
572 // removed since we can then embed iframes in different processes.
573 virtual bool IsSubframe() const = 0;
575 // Finds text on a page.
576 virtual void Find(int request_id,
577 const base::string16& search_text,
578 const blink::WebFindOptions& options) = 0;
580 // Notifies the renderer that the user has closed the FindInPage window
581 // (and what action to take regarding the selection).
582 virtual void StopFinding(StopFindAction action) = 0;
584 // Requests the renderer to insert CSS into the main frame's document.
585 virtual void InsertCSS(const std::string& css) = 0;
587 // Returns true if audio has recently been audible from the WebContents.
588 virtual bool WasRecentlyAudible() = 0;
590 typedef base::Callback<void(const Manifest&)> GetManifestCallback;
592 // Requests the Manifest of the main frame's document.
593 virtual void GetManifest(const GetManifestCallback&) = 0;
595 #if defined(OS_ANDROID)
596 CONTENT_EXPORT static WebContents* FromJavaWebContents(
597 jobject jweb_contents_android);
598 virtual base::android::ScopedJavaLocalRef<jobject> GetJavaWebContents() = 0;
599 #elif defined(OS_MACOSX)
600 // Allowing other views disables optimizations which assume that only a single
601 // WebContents is present.
602 virtual void SetAllowOtherViews(bool allow) = 0;
604 // Returns true if other views are allowed, false otherwise.
605 virtual bool GetAllowOtherViews() = 0;
609 // This interface should only be implemented inside content.
610 friend class WebContentsImpl;
614 } // namespace content
616 #endif // CONTENT_PUBLIC_BROWSER_WEB_CONTENTS_H_