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.
4 
5 #ifndef CONTENT_PUBLIC_BROWSER_WEB_CONTENTS_OBSERVER_H_
6 #define CONTENT_PUBLIC_BROWSER_WEB_CONTENTS_OBSERVER_H_
7 
8 #include <stdint.h>
9 
10 #include "base/macros.h"
11 #include "base/optional.h"
12 #include "base/process/kill.h"
13 #include "base/process/process_handle.h"
14 #include "components/viz/common/vertical_scroll_direction.h"
15 #include "content/common/content_export.h"
16 #include "content/public/browser/navigation_controller.h"
17 #include "content/public/browser/reload_type.h"
18 #include "content/public/browser/visibility.h"
19 #include "content/public/common/frame_navigate_params.h"
20 #include "ipc/ipc_listener.h"
21 #include "mojo/public/cpp/system/message_pipe.h"
22 #include "services/network/public/mojom/fetch_api.mojom-forward.h"
23 #include "services/service_manager/public/cpp/bind_source_info.h"
24 #include "third_party/blink/public/common/input/web_input_event.h"
25 #include "third_party/blink/public/common/user_agent/user_agent_metadata.h"
26 #include "third_party/blink/public/mojom/devtools/console_message.mojom.h"
27 #include "third_party/blink/public/mojom/loader/resource_load_info.mojom-forward.h"
28 #include "third_party/skia/include/core/SkColor.h"
29 #include "ui/base/page_transition_types.h"
30 #include "ui/base/window_open_disposition.h"
31 
32 namespace blink {
33 namespace mojom {
34 enum class ViewportFit;
35 }  // namespace mojom
36 }  // namespace blink
37 
38 namespace gfx {
39 class Size;
40 }  // namespace gfx
41 
42 namespace content {
43 
44 class NavigationEntry;
45 class NavigationHandle;
46 class RenderFrameHost;
47 class RenderProcessHost;
48 class RenderViewHost;
49 class RenderWidgetHost;
50 class WebContents;
51 class WebContentsImpl;
52 struct AXEventNotificationDetails;
53 struct AXLocationChangeNotificationDetails;
54 struct EntryChangedDetails;
55 struct FocusedNodeDetails;
56 struct LoadCommittedDetails;
57 struct MediaPlayerId;
58 struct PrunedDetails;
59 struct Referrer;
60 
61 // An observer API implemented by classes which are interested in various page
62 // load events from WebContents.  They also get a chance to filter IPC messages.
63 //
64 // Since a WebContents can be a delegate to almost arbitrarily many
65 // RenderViewHosts, it is important to check in those WebContentsObserver
66 // methods which take a RenderViewHost that the event came from the
67 // RenderViewHost the observer cares about.
68 //
69 // Usually, observers should only care about the current RenderViewHost as
70 // returned by GetRenderViewHost().
71 //
72 // TODO(creis, jochen): Hide the fact that there are several RenderViewHosts
73 // from the WebContentsObserver API. http://crbug.com/173325
74 class CONTENT_EXPORT WebContentsObserver : public IPC::Listener {
75  public:
76   // Frames and Views ----------------------------------------------------------
77 
78   // Called when a RenderFrame for |render_frame_host| is created in the
79   // renderer process. Use |RenderFrameDeleted| to listen for when this
80   // RenderFrame goes away.
RenderFrameCreated(RenderFrameHost * render_frame_host)81   virtual void RenderFrameCreated(RenderFrameHost* render_frame_host) {}
82 
83   // Called when a RenderFrame for |render_frame_host| is deleted or the
84   // renderer process in which it runs it has died. Use |RenderFrameCreated| to
85   // listen for when RenderFrame objects are created.
RenderFrameDeleted(RenderFrameHost * render_frame_host)86   virtual void RenderFrameDeleted(RenderFrameHost* render_frame_host) {}
87 
88   // This method is invoked whenever one of the current frames of a WebContents
89   // swaps its RenderFrameHost with another one; for example because that frame
90   // navigated and the new content is in a different process. The
91   // RenderFrameHost that has been replaced is in |old_host|, which can be
92   // nullptr if the old RenderFrameHost was shut down or a new frame has been
93   // created and no old RenderFrameHost exists.
94   //
95   // This method, in combination with |FrameDeleted|, is appropriate for
96   // observers wishing to track the set of current RenderFrameHosts -- i.e.,
97   // those hosts that would be visited by calling WebContents::ForEachFrame().
RenderFrameHostChanged(RenderFrameHost * old_host,RenderFrameHost * new_host)98   virtual void RenderFrameHostChanged(RenderFrameHost* old_host,
99                                       RenderFrameHost* new_host) {}
100 
101   // This method is invoked when a subframe associated with a WebContents is
102   // deleted or the WebContents is destroyed and the top-level frame is deleted.
103   // Use |RenderFrameHostChanged| to listen for when a RenderFrameHost object is
104   // made the current host for a frame.
FrameDeleted(RenderFrameHost * render_frame_host)105   virtual void FrameDeleted(RenderFrameHost* render_frame_host) {}
106 
107   // This is called when a RVH is created for a WebContents, but not if it's an
108   // interstitial.
RenderViewCreated(RenderViewHost * render_view_host)109   virtual void RenderViewCreated(RenderViewHost* render_view_host) {}
110 
111   // Called for every RenderFrameHost that's created for an interstitial.
RenderFrameForInterstitialPageCreated(RenderFrameHost * render_frame_host)112   virtual void RenderFrameForInterstitialPageCreated(
113       RenderFrameHost* render_frame_host) {}
114 
115   // This method is invoked when the RenderView of the current RenderViewHost
116   // is ready, e.g. because we recreated it after a crash.
RenderViewReady()117   virtual void RenderViewReady() {}
118 
119   // This method is invoked when a RenderViewHost of the WebContents is
120   // deleted. Note that this does not always happen when the WebContents starts
121   // to use a different RenderViewHost, as the old RenderViewHost might get
122   // just swapped out.
RenderViewDeleted(RenderViewHost * render_view_host)123   virtual void RenderViewDeleted(RenderViewHost* render_view_host) {}
124 
125   // This method is invoked when the process for the current main
126   // RenderFrameHost exits (usually by crashing, though possibly by other
127   // means). The WebContents continues to use the RenderFrameHost, e.g. when the
128   // user reloads the current page. When the RenderFrameHost itself is deleted,
129   // the RenderFrameDeleted method will be invoked.
130   //
131   // Note that this is triggered upstream through
132   // RenderProcessHostObserver::RenderProcessExited(); for code that doesn't
133   // otherwise need to be a WebContentsObserver, that API is probably a better
134   // choice.
RenderProcessGone(base::TerminationStatus status)135   virtual void RenderProcessGone(base::TerminationStatus status) {}
136 
137   // This method is invoked when a WebContents swaps its visible RenderViewHost
138   // with another one, possibly changing processes. The RenderViewHost that has
139   // been replaced is in |old_host|, which is nullptr if the old RVH was shut
140   // down.
RenderViewHostChanged(RenderViewHost * old_host,RenderViewHost * new_host)141   virtual void RenderViewHostChanged(RenderViewHost* old_host,
142                                      RenderViewHost* new_host) {}
143 
144   // This method is invoked when a process in the WebContents becomes
145   // unresponsive.
OnRendererUnresponsive(RenderProcessHost * render_process_host)146   virtual void OnRendererUnresponsive(RenderProcessHost* render_process_host) {}
147 
148   // Navigation ----------------------------------------------------------------
149 
150   // Called when a navigation started in the WebContents. |navigation_handle|
151   // is unique to a specific navigation. The same |navigation_handle| will be
152   // provided on subsequent calls to DidRedirectNavigation, DidFinishNavigation,
153   // and ReadyToCommitNavigation when related to this navigation. Observers
154   // should clear any references to |navigation_handle| in DidFinishNavigation,
155   // just before it is destroyed.
156   //
157   // Note that this is fired by navigations in any frame of the WebContents,
158   // not just the main frame.
159   //
160   // Note that this is fired by same-document navigations, such as fragment
161   // navigations or pushState/replaceState, which will not result in a document
162   // change. To filter these out, use NavigationHandle::IsSameDocument.
163   //
164   // Note that more than one navigation can be ongoing in the same frame at the
165   // same time (including the main frame). Each will get its own
166   // NavigationHandle.
167   //
168   // Note that there is no guarantee that DidFinishNavigation will be called
169   // for any particular navigation before DidStartNavigation is called on the
170   // next.
DidStartNavigation(NavigationHandle * navigation_handle)171   virtual void DidStartNavigation(NavigationHandle* navigation_handle) {}
172 
173   // Called when a navigation encountered a server redirect.
DidRedirectNavigation(NavigationHandle * navigation_handle)174   virtual void DidRedirectNavigation(NavigationHandle* navigation_handle) {}
175 
176   // Called when the navigation is ready to be committed in a renderer. This
177   // occurs when the response code isn't 204/205 (which tell the browser that
178   // the request is successful but there's no content that follows) or a
179   // download (either from a response header or based on mime sniffing the
180   // response). The browser then is ready to switch rendering the new document.
181   // Most observers should use DidFinishNavigation instead, which happens right
182   // after the navigation commits. This method is for observers that want to
183   // initialize renderer-side state just before the RenderFrame commits the
184   // navigation.
185   //
186   // This is the first point in time where a RenderFrameHost is associated with
187   // the navigation.
ReadyToCommitNavigation(NavigationHandle * navigation_handle)188   virtual void ReadyToCommitNavigation(NavigationHandle* navigation_handle) {}
189 
190   // Called when a navigation finished in the WebContents. This happens when a
191   // navigation is committed, aborted or replaced by a new one. To know if the
192   // navigation has committed, use NavigationHandle::HasCommitted; use
193   // NavigationHandle::IsErrorPage to know if the navigation resulted in an
194   // error page.
195   //
196   // If this is called because the navigation committed, then the document load
197   // will still be ongoing in the RenderFrameHost returned by
198   // |navigation_handle|. Use the document loads events such as DidStopLoading
199   // and related methods to listen for continued events from this
200   // RenderFrameHost.
201   //
202   // Note that this is fired by same-document navigations, such as fragment
203   // navigations or pushState/replaceState, which will not result in a document
204   // change. To filter these out, use NavigationHandle::IsSameDocument.
205   //
206   // Note that |navigation_handle| will be destroyed at the end of this call,
207   // so do not keep a reference to it afterward.
DidFinishNavigation(NavigationHandle * navigation_handle)208   virtual void DidFinishNavigation(NavigationHandle* navigation_handle) {}
209 
210   // Navigation (obsolete and deprecated) --------------------------------------
211 
212   // This method is invoked after the browser process starts a navigation to a
213   // pending NavigationEntry. It is not called for renderer-initiated
214   // navigations unless they are sent to the browser process via OpenURL. It may
215   // be called multiple times for a given navigation, such as a typed URL
216   // followed by a cross-process client or server redirect.
217   //
218   // SOON TO BE DEPRECATED. Use DidStartNavigation instead.
219   // TODO(clamy): Remove this function.
DidStartNavigationToPendingEntry(const GURL & url,ReloadType reload_type)220   virtual void DidStartNavigationToPendingEntry(const GURL& url,
221                                                 ReloadType reload_type) {}
222 
223   // Document load events ------------------------------------------------------
224 
225   // These three methods correspond to the points in time when a document starts
226   // loading for the first time (initiates outgoing requests), when incoming
227   // data subsequently starts arriving, and when it finishes loading.
DidStartLoading()228   virtual void DidStartLoading() {}
DidReceiveResponse()229   virtual void DidReceiveResponse() {}
DidStopLoading()230   virtual void DidStopLoading() {}
231 
232   // The page has made some progress loading. |progress| is a value between 0.0
233   // (nothing loaded) to 1.0 (page fully loaded).
LoadProgressChanged(double progress)234   virtual void LoadProgressChanged(double progress) {}
235 
236   // This method is invoked once the window.document object of the main frame
237   // was created.
DocumentAvailableInMainFrame()238   virtual void DocumentAvailableInMainFrame() {}
239 
240   // This method is invoked once the onload handler of the main frame has
241   // completed.
242   // Prefer using WebContents::IsDocumentOnLoadCompletedInMainFrame instead
243   // of saving this state in your component.
DocumentOnLoadCompletedInMainFrame()244   virtual void DocumentOnLoadCompletedInMainFrame() {}
245 
246   // This method is invoked when the document in the given frame finished
247   // loading. At this point, scripts marked as defer were executed, and
248   // content scripts marked "document_end" get injected into the frame.
DOMContentLoaded(RenderFrameHost * render_frame_host)249   virtual void DOMContentLoaded(RenderFrameHost* render_frame_host) {}
250 
251   // This method is invoked when the load is done, i.e. the spinner of the tab
252   // will stop spinning, and the onload event was dispatched.
253   //
254   // If the WebContents is displaying replacement content, e.g. network error
255   // pages, DidFinishLoad is invoked for frames that were not sending
256   // navigational events before. It is safe to ignore these events.
DidFinishLoad(RenderFrameHost * render_frame_host,const GURL & validated_url)257   virtual void DidFinishLoad(RenderFrameHost* render_frame_host,
258                              const GURL& validated_url) {}
259 
260   // This method is like DidFinishLoad, but when the load failed or was
261   // cancelled, e.g. window.stop() is invoked.
DidFailLoad(RenderFrameHost * render_frame_host,const GURL & validated_url,int error_code)262   virtual void DidFailLoad(RenderFrameHost* render_frame_host,
263                            const GURL& validated_url,
264                            int error_code) {}
265 
266   // This method is invoked when the visible security state of the page changes.
DidChangeVisibleSecurityState()267   virtual void DidChangeVisibleSecurityState() {}
268 
269   // This method is invoked when content was loaded from an in-memory cache.
DidLoadResourceFromMemoryCache(const GURL & url,const std::string & mime_type,network::mojom::RequestDestination request_destination)270   virtual void DidLoadResourceFromMemoryCache(
271       const GURL& url,
272       const std::string& mime_type,
273       network::mojom::RequestDestination request_destination) {}
274 
275   // This method is invoked when a resource associate with the frame
276   // |render_frame_host| has been loaded, successfully or not. |request_id| will
277   // only be populated for main frame resources.
ResourceLoadComplete(RenderFrameHost * render_frame_host,const GlobalRequestID & request_id,const blink::mojom::ResourceLoadInfo & resource_load_info)278   virtual void ResourceLoadComplete(
279       RenderFrameHost* render_frame_host,
280       const GlobalRequestID& request_id,
281       const blink::mojom::ResourceLoadInfo& resource_load_info) {}
282 
283   // This method is invoked when a document or resource reads a cookie. Note
284   // that this isn't tied to any particular navigation (e.g., it may be called
285   // after a subsequent navigation commits).
OnCookiesRead(const GURL & url,const GURL & first_party_url,const net::CookieList & cookie_list,bool blocked_by_policy)286   virtual void OnCookiesRead(const GURL& url,
287                              const GURL& first_party_url,
288                              const net::CookieList& cookie_list,
289                              bool blocked_by_policy) {}
290 
291   // This method is invoked when an attempt has been made to set |cookie|. Note
292   // that this isn't tied to any particular navigation (e.g., it may be called
293   // after a subsequent navigation commits).
OnCookieChange(const GURL & url,const GURL & first_party_url,const net::CanonicalCookie & cookie,bool blocked_by_policy)294   virtual void OnCookieChange(const GURL& url,
295                               const GURL& first_party_url,
296                               const net::CanonicalCookie& cookie,
297                               bool blocked_by_policy) {}
298 
299   // This method is invoked when a new non-pending navigation entry is created.
300   // This corresponds to one NavigationController entry being created
301   // (in the case of new navigations) or renavigated to (for back/forward
302   // navigations).
NavigationEntryCommitted(const LoadCommittedDetails & load_details)303   virtual void NavigationEntryCommitted(
304       const LoadCommittedDetails& load_details) {}
305 
306   // Invoked when the NavigationController decreased its back/forward list count
307   // by removing entries from either the front or back of its list. This is
308   // usually the result of going back and then doing a new navigation, meaning
309   // all the "forward" items are deleted.
310   //
311   // This normally happens as a result of a new navigation. It will be
312   // followed by a NavigationEntryCommitted() call for the new page that
313   // caused the pruning. It could also be a result of removing an item from
314   // the list to delete history or fix up after interstitials.
NavigationListPruned(const PrunedDetails & pruned_details)315   virtual void NavigationListPruned(const PrunedDetails& pruned_details) {}
316 
317   // Invoked when NavigationEntries have been deleted because of a history
318   // deletion. Observers should ensure that they remove all traces of the
319   // deleted entries.
NavigationEntriesDeleted()320   virtual void NavigationEntriesDeleted() {}
321 
322   // Invoked when a NavigationEntry has changed.
323   //
324   // This will NOT be sent on navigation, interested parties should also
325   // implement NavigationEntryCommitted() to handle that case. This will be
326   // sent when the entry is updated outside of navigation (like when a new
327   // title comes).
NavigationEntryChanged(const EntryChangedDetails & change_details)328   virtual void NavigationEntryChanged(
329       const EntryChangedDetails& change_details) {}
330 
331   // This method is invoked when a new WebContents was created in response to
332   // an action in the observed WebContents, e.g. a link with target=_blank was
333   // clicked. The |source_render_frame_host| is the frame in which the action
334   // took place.
DidOpenRequestedURL(WebContents * new_contents,RenderFrameHost * source_render_frame_host,const GURL & url,const Referrer & referrer,WindowOpenDisposition disposition,ui::PageTransition transition,bool started_from_context_menu,bool renderer_initiated)335   virtual void DidOpenRequestedURL(WebContents* new_contents,
336                                    RenderFrameHost* source_render_frame_host,
337                                    const GURL& url,
338                                    const Referrer& referrer,
339                                    WindowOpenDisposition disposition,
340                                    ui::PageTransition transition,
341                                    bool started_from_context_menu,
342                                    bool renderer_initiated) {}
343 
344   // This method is invoked when the renderer process has completed its first
345   // paint after a non-empty layout.
DidFirstVisuallyNonEmptyPaint()346   virtual void DidFirstVisuallyNonEmptyPaint() {}
347 
348   // When WebContents::Stop() is called, the WebContents stops loading and then
349   // invokes this method. If there are ongoing navigations, their respective
350   // failure methods will also be invoked.
NavigationStopped()351   virtual void NavigationStopped() {}
352 
353   // Called when there has been direct user interaction with the WebContents.
354   // The type argument specifies the kind of interaction. Direct user input
355   // signalled through this callback includes:
356   // 1) any mouse down event (blink::WebInputEvent::MouseDown);
357   // 2) the start of a scroll (blink::WebInputEvent::GestureScrollBegin);
358   // 3) any raw key down event (blink::WebInputEvent::RawKeyDown); and
359   // 4) any touch event (inc. scrolls) (blink::WebInputEvent::TouchStart).
DidGetUserInteraction(const blink::WebInputEvent::Type type)360   virtual void DidGetUserInteraction(const blink::WebInputEvent::Type type) {}
361 
362   // This method is invoked when a RenderViewHost of this WebContents was
363   // configured to ignore UI events, and an UI event took place.
DidGetIgnoredUIEvent()364   virtual void DidGetIgnoredUIEvent() {}
365 
366   // Invoked every time the WebContents changes visibility.
OnVisibilityChanged(Visibility visibility)367   virtual void OnVisibilityChanged(Visibility visibility) {}
368 
369   // Invoked when the main frame changes size.
MainFrameWasResized(bool width_changed)370   virtual void MainFrameWasResized(bool width_changed) {}
371 
372   // Invoked when the given frame changes its window.name property.
FrameNameChanged(RenderFrameHost * render_frame_host,const std::string & name)373   virtual void FrameNameChanged(RenderFrameHost* render_frame_host,
374                                 const std::string& name) {}
375 
376   // Called when the sticky user activation bit has been set on the frame.
377   // This will not be called for new RenderFrameHosts whose underlying
378   // FrameTreeNode was already activated. This should not be used to determine a
379   // RenderFrameHost's user activation state.
FrameReceivedFirstUserActivation(RenderFrameHost * render_frame_host)380   virtual void FrameReceivedFirstUserActivation(
381       RenderFrameHost* render_frame_host) {}
382 
383   // Invoked when the display state of the frame changes.
FrameDisplayStateChanged(RenderFrameHost * render_frame_host,bool is_display_none)384   virtual void FrameDisplayStateChanged(RenderFrameHost* render_frame_host,
385                                         bool is_display_none) {}
386 
387   // Invoked when a frame changes size.
FrameSizeChanged(RenderFrameHost * render_frame_host,const gfx::Size & frame_size)388   virtual void FrameSizeChanged(RenderFrameHost* render_frame_host,
389                                 const gfx::Size& frame_size) {}
390 
391   // This method is invoked when the title of the WebContents is set. Note that
392   // |entry| may be null if the web page whose title changed has not yet had a
393   // NavigationEntry assigned to it.
TitleWasSet(NavigationEntry * entry)394   virtual void TitleWasSet(NavigationEntry* entry) {}
395 
AppCacheAccessed(const GURL & manifest_url,bool blocked_by_policy)396   virtual void AppCacheAccessed(const GURL& manifest_url,
397                                 bool blocked_by_policy) {}
398 
399   // These methods are invoked when a Pepper plugin instance is created/deleted
400   // in the DOM.
PepperInstanceCreated()401   virtual void PepperInstanceCreated() {}
PepperInstanceDeleted()402   virtual void PepperInstanceDeleted() {}
403 
404   // This method is called when the viewport fit of a WebContents changes.
ViewportFitChanged(blink::mojom::ViewportFit value)405   virtual void ViewportFitChanged(blink::mojom::ViewportFit value) {}
406 
407   // Notification that a plugin has crashed.
408   // |plugin_pid| is the process ID identifying the plugin process. Note that
409   // this ID is supplied by the renderer process, so should not be trusted.
410   // Besides, the corresponding process has probably died at this point. The ID
411   // may even have been reused by a new process.
PluginCrashed(const base::FilePath & plugin_path,base::ProcessId plugin_pid)412   virtual void PluginCrashed(const base::FilePath& plugin_path,
413                              base::ProcessId plugin_pid) {}
414 
415   // Notification that the given plugin has hung or become unhung. This
416   // notification is only for Pepper plugins.
417   //
418   // The plugin_child_id is the unique child process ID from the plugin. Note
419   // that this ID is supplied by the renderer process, so should be validated
420   // before it's used for anything in case there's an exploited renderer
421   // process.
PluginHungStatusChanged(int plugin_child_id,const base::FilePath & plugin_path,bool is_hung)422   virtual void PluginHungStatusChanged(int plugin_child_id,
423                                        const base::FilePath& plugin_path,
424                                        bool is_hung) {}
425 
426   // Notifies that an inner WebContents instance has been created with the
427   // observed WebContents as its container. |inner_web_contents| has not been
428   // added to the WebContents tree at this point, but can be observed safely.
InnerWebContentsCreated(WebContents * inner_web_contents)429   virtual void InnerWebContentsCreated(WebContents* inner_web_contents) {}
430 
431   // Invoked when WebContents::Clone() was used to clone a WebContents.
DidCloneToNewWebContents(WebContents * old_web_contents,WebContents * new_web_contents)432   virtual void DidCloneToNewWebContents(WebContents* old_web_contents,
433                                         WebContents* new_web_contents) {}
434 
435   // Invoked when the WebContents is being destroyed. Gives subclasses a chance
436   // to cleanup. After the whole loop over all WebContentsObservers has been
437   // finished, web_contents() returns nullptr.
WebContentsDestroyed()438   virtual void WebContentsDestroyed() {}
439 
440   // Called when the user agent override for a WebContents has been changed.
UserAgentOverrideSet(const blink::UserAgentOverride & ua_override)441   virtual void UserAgentOverrideSet(
442       const blink::UserAgentOverride& ua_override) {}
443 
444   // Invoked when new blink::mojom::FaviconURLPtr candidates are received from
445   // the renderer process. If the instance is created after the page is loaded,
446   // it is recommended to call WebContents::GetFaviconURLs() to get the current
447   // list as this callback will not be executed unless there is an update.
DidUpdateFaviconURL(const std::vector<blink::mojom::FaviconURLPtr> & candidates)448   virtual void DidUpdateFaviconURL(
449       const std::vector<blink::mojom::FaviconURLPtr>& candidates) {}
450 
451   // Called when an audio change occurs.
OnAudioStateChanged(bool audible)452   virtual void OnAudioStateChanged(bool audible) {}
453 
454   // Called when the connected to Bluetooth device state changes.
OnIsConnectedToBluetoothDeviceChanged(bool is_connected_to_bluetooth_device)455   virtual void OnIsConnectedToBluetoothDeviceChanged(
456       bool is_connected_to_bluetooth_device) {}
457 
458   // Invoked when the WebContents is muted/unmuted.
DidUpdateAudioMutingState(bool muted)459   virtual void DidUpdateAudioMutingState(bool muted) {}
460 
461   // Invoked when a pepper plugin creates and shows or destroys a fullscreen
462   // RenderWidget.
DidShowFullscreenWidget()463   virtual void DidShowFullscreenWidget() {}
DidDestroyFullscreenWidget()464   virtual void DidDestroyFullscreenWidget() {}
465 
466   // Invoked when the renderer process has toggled the tab into/out of
467   // fullscreen mode.
DidToggleFullscreenModeForTab(bool entered_fullscreen,bool will_cause_resize)468   virtual void DidToggleFullscreenModeForTab(bool entered_fullscreen,
469                                              bool will_cause_resize) {}
470 
471   // Signals that |rfh| has the current fullscreen element. This is invoked
472   // when:
473   //  1) an element in this frame enters fullscreen or in nested fullscreen, or
474   //  2) after an element in a descendant frame exits fullscreen and makes
475   //     this frame own the current fullscreen element again.
DidAcquireFullscreen(RenderFrameHost * rfh)476   virtual void DidAcquireFullscreen(RenderFrameHost* rfh) {}
477 
478   // Invoked when an interstitial page is attached or detached.
DidAttachInterstitialPage()479   virtual void DidAttachInterstitialPage() {}
DidDetachInterstitialPage()480   virtual void DidDetachInterstitialPage() {}
481 
482   // Invoked when the vertical scroll direction of the root layer is changed.
483   // Note that if a scroll in a given direction occurs, the scroll is completed,
484   // and then another scroll in the *same* direction occurs, we will not
485   // consider the second scroll event to have caused a change in direction. Also
486   // note that this API will *never* be called with |kNull| which only exists to
487   // indicate the absence of a vertical scroll direction.
DidChangeVerticalScrollDirection(viz::VerticalScrollDirection scroll_direction)488   virtual void DidChangeVerticalScrollDirection(
489       viz::VerticalScrollDirection scroll_direction) {}
490 
491   // Invoked before a form repost warning is shown.
BeforeFormRepostWarningShow()492   virtual void BeforeFormRepostWarningShow() {}
493 
494   // Invoked when the beforeunload handler fires. |proceed| is set to true if
495   // the beforeunload can safely proceed, otherwise it should be interrupted.
496   // The time is from the renderer process.
BeforeUnloadFired(bool proceed,const base::TimeTicks & proceed_time)497   virtual void BeforeUnloadFired(bool proceed,
498                                  const base::TimeTicks& proceed_time) {}
499 
500   // Invoked when a user cancels a before unload dialog.
BeforeUnloadDialogCancelled()501   virtual void BeforeUnloadDialogCancelled() {}
502 
503   // Called when accessibility events or location changes are received
504   // from a render frame, but only when the accessibility mode has the
505   // ui::AXMode::kWebContents flag set.
AccessibilityEventReceived(const AXEventNotificationDetails & details)506   virtual void AccessibilityEventReceived(
507       const AXEventNotificationDetails& details) {}
AccessibilityLocationChangesReceived(const std::vector<AXLocationChangeNotificationDetails> & details)508   virtual void AccessibilityLocationChangesReceived(
509       const std::vector<AXLocationChangeNotificationDetails>& details) {}
510 
511   // Invoked when theme color is changed.
DidChangeThemeColor()512   virtual void DidChangeThemeColor() {}
513 
514   // Called when a message is added to the console of the WebContents. This is
515   // invoked before forwarding the message to the WebContents' delegate.
OnDidAddMessageToConsole(blink::mojom::ConsoleMessageLevel log_level,const base::string16 & message,int32_t line_no,const base::string16 & source_id)516   virtual void OnDidAddMessageToConsole(
517       blink::mojom::ConsoleMessageLevel log_level,
518       const base::string16& message,
519       int32_t line_no,
520       const base::string16& source_id) {}
521 
522   // Invoked when media is playing or paused.  |id| is unique per player and per
523   // RenderFrameHost.  There may be multiple players within a RenderFrameHost
524   // and subsequently within a WebContents.  MediaStartedPlaying() will always
525   // be followed by MediaStoppedPlaying() after player teardown.  Observers must
526   // release all stored copies of |id| when MediaStoppedPlaying() is received.
527   // |has_video| and |has_audio| can both be false in cases where the media
528   // is playing muted and should be considered as inaudible for all intent and
529   // purposes.
530   struct MediaPlayerInfo {
MediaPlayerInfoMediaPlayerInfo531     MediaPlayerInfo(bool has_video, bool has_audio)
532         : has_video(has_video), has_audio(has_audio) {}
533     bool has_video;
534     bool has_audio;
535   };
536 
MediaStartedPlaying(const MediaPlayerInfo & video_type,const MediaPlayerId & id)537   virtual void MediaStartedPlaying(const MediaPlayerInfo& video_type,
538                                    const MediaPlayerId& id) {}
539   enum class MediaStoppedReason {
540     // The media was stopped for an unspecified reason.
541     kUnspecified,
542 
543     // The media was stopped because it reached the end of the stream.
544     kReachedEndOfStream,
545   };
MediaStoppedPlaying(const MediaPlayerInfo & video_type,const MediaPlayerId & id,WebContentsObserver::MediaStoppedReason reason)546   virtual void MediaStoppedPlaying(
547       const MediaPlayerInfo& video_type,
548       const MediaPlayerId& id,
549       WebContentsObserver::MediaStoppedReason reason) {}
MediaResized(const gfx::Size & size,const MediaPlayerId & id)550   virtual void MediaResized(const gfx::Size& size, const MediaPlayerId& id) {}
551   // Invoked when media enters or exits fullscreen. We must use a heuristic
552   // to determine this as it is not trivial for media with custom controls.
553   // There is a slight delay between media entering or exiting fullscreen
554   // and it being detected.
MediaEffectivelyFullscreenChanged(bool is_fullscreen)555   virtual void MediaEffectivelyFullscreenChanged(bool is_fullscreen) {}
MediaPictureInPictureChanged(bool is_picture_in_picture)556   virtual void MediaPictureInPictureChanged(bool is_picture_in_picture) {}
MediaMutedStatusChanged(const MediaPlayerId & id,bool muted)557   virtual void MediaMutedStatusChanged(const MediaPlayerId& id, bool muted) {}
558 
559   // Invoked when the renderer process changes the page scale factor.
OnPageScaleFactorChanged(float page_scale_factor)560   virtual void OnPageScaleFactorChanged(float page_scale_factor) {}
561 
562   // Invoked when a paste event occurs.
OnPaste()563   virtual void OnPaste() {}
564 
565   // Invoked if an IPC message is coming from a specific RenderFrameHost.
566   virtual bool OnMessageReceived(const IPC::Message& message,
567                                  RenderFrameHost* render_frame_host);
568 
569   // Notification that the |render_widget_host| for this WebContents has gained
570   // focus.
OnWebContentsFocused(RenderWidgetHost * render_widget_host)571   virtual void OnWebContentsFocused(RenderWidgetHost* render_widget_host) {}
572 
573   // Notification that the |render_widget_host| for this WebContents has lost
574   // focus.
OnWebContentsLostFocus(RenderWidgetHost * render_widget_host)575   virtual void OnWebContentsLostFocus(RenderWidgetHost* render_widget_host) {}
576 
577   // Notification that a RenderFrameHost inside this WebContents has updated
578   // its focused element. |details| contains information on the element
579   // that has received focus. This allows for observing focus changes
580   // within WebContents, as opposed to OnWebContentsFocused/LostFocus
581   // which allows observation that the RenderWidgetHost for the
582   // WebContents has gained/lost focus.
OnFocusChangedInPage(FocusedNodeDetails * details)583   virtual void OnFocusChangedInPage(FocusedNodeDetails* details) {}
584 
585   // Notifies that the manifest URL for the main frame changed to
586   // |manifest_url|. This will be invoked when a document with a manifest loads
587   // or when the manifest URL changes (possibly to nothing). It is not invoked
588   // when a document with no manifest loads. During document load, if the
589   // document has both a manifest and a favicon, DidUpdateWebManifestURL() will
590   // be invoked before DidUpdateFaviconURL().
DidUpdateWebManifestURL(const base::Optional<GURL> & manifest_url)591   virtual void DidUpdateWebManifestURL(
592       const base::Optional<GURL>& manifest_url) {}
593 
594   // DEPRECATED. Please register interface binders with BrowserInterfaceBroker
595   // instead (see 'Interface-Brokers' section in //docs/mojo_and_services.md).
596   // Called to give the embedder an opportunity to bind an interface request
597   // from a frame. If the request can be bound, |interface_pipe| will be taken.
OnInterfaceRequestFromFrame(RenderFrameHost * render_frame_host,const std::string & interface_name,mojo::ScopedMessagePipeHandle * interface_pipe)598   virtual void OnInterfaceRequestFromFrame(
599       RenderFrameHost* render_frame_host,
600       const std::string& interface_name,
601       mojo::ScopedMessagePipeHandle* interface_pipe) {}
602 
603   // Called when "audible" playback starts or stops on a WebAudio AudioContext.
604   using AudioContextId = std::pair<RenderFrameHost*, int>;
AudioContextPlaybackStarted(const AudioContextId & audio_context_id)605   virtual void AudioContextPlaybackStarted(
606       const AudioContextId& audio_context_id) {}
AudioContextPlaybackStopped(const AudioContextId & audio_context_id)607   virtual void AudioContextPlaybackStopped(
608       const AudioContextId& audio_context_id) {}
609 
610   // IPC::Listener implementation.
611   // DEPRECATED: Use (i.e. override) the other overload instead:
612   //     virtual bool OnMessageReceived(const IPC::Message& message,
613   //                                    RenderFrameHost* render_frame_host);
614   // TODO(https://crbug.com/758026): Delete this overload when possible.
615   bool OnMessageReceived(const IPC::Message& message) override;
616 
617   WebContents* web_contents() const;
618 
619  protected:
620   // Use this constructor when the object is tied to a single WebContents for
621   // its entire lifetime.
622   explicit WebContentsObserver(WebContents* web_contents);
623 
624   // Use this constructor when the object wants to observe a WebContents for
625   // part of its lifetime.  It can then call Observe() to start and stop
626   // observing.
627   WebContentsObserver();
628 
629   ~WebContentsObserver() override;
630 
631   // Start observing a different WebContents; used with the default constructor.
632   void Observe(WebContents* web_contents);
633 
634  private:
635   friend class WebContentsImpl;
636 
637   void ResetWebContents();
638 
639   WebContentsImpl* web_contents_;
640 
641   DISALLOW_COPY_AND_ASSIGN(WebContentsObserver);
642 };
643 
644 }  // namespace content
645 
646 #endif  // CONTENT_PUBLIC_BROWSER_WEB_CONTENTS_OBSERVER_H_
647