Add callback in UserScriptLoader to notify users when scripts are loaded.
[chromium-blink-merge.git] / extensions / browser / guest_view / web_view / web_view_guest.h
blobdcfd378a7907160966ee4e590cdd0701e9a6c2cf
1 // Copyright 2014 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 EXTENSIONS_BROWSER_GUEST_VIEW_WEB_VIEW_WEB_VIEW_GUEST_H_
6 #define EXTENSIONS_BROWSER_GUEST_VIEW_WEB_VIEW_WEB_VIEW_GUEST_H_
8 #include <vector>
10 #include "base/observer_list.h"
11 #include "components/guest_view/browser/guest_view.h"
12 #include "content/public/browser/javascript_dialog_manager.h"
13 #include "content/public/browser/notification_observer.h"
14 #include "content/public/browser/notification_registrar.h"
15 #include "extensions/browser/guest_view/web_view/javascript_dialog_helper.h"
16 #include "extensions/browser/guest_view/web_view/web_view_find_helper.h"
17 #include "extensions/browser/guest_view/web_view/web_view_guest_delegate.h"
18 #include "extensions/browser/guest_view/web_view/web_view_permission_helper.h"
19 #include "extensions/browser/guest_view/web_view/web_view_permission_types.h"
20 #include "extensions/browser/script_executor.h"
22 namespace blink {
23 struct WebFindOptions;
24 } // nanespace blink
26 namespace extensions {
28 class WebViewInternalFindFunction;
30 // A WebViewGuest provides the browser-side implementation of the <webview> API
31 // and manages the dispatch of <webview> extension events. WebViewGuest is
32 // created on attachment. That is, when a guest WebContents is associated with
33 // a particular embedder WebContents. This happens on either initial navigation
34 // or through the use of the New Window API, when a new window is attached to
35 // a particular <webview>.
36 class WebViewGuest : public guest_view::GuestView<WebViewGuest>,
37 public content::NotificationObserver {
38 public:
39 static GuestViewBase* Create(content::WebContents* owner_web_contents);
41 // For WebViewGuest, we create special guest processes, which host the
42 // tag content separately from the main application that embeds the tag.
43 // A <webview> can specify both the partition name and whether the storage
44 // for that partition should be persisted. Each tag gets a SiteInstance with
45 // a specially formatted URL, based on the application it is hosted by and
46 // the partition requested by it. The format for that URL is:
47 // chrome-guest://partition_domain/persist?partition_name
48 static bool GetGuestPartitionConfigForSite(const GURL& site,
49 std::string* partition_domain,
50 std::string* partition_name,
51 bool* in_memory);
53 // Returns guest_view::kInstanceIDNone if |contents| does not correspond to a
54 // WebViewGuest.
55 static int GetViewInstanceId(content::WebContents* contents);
57 static const char Type[];
59 // Returns the stored rules registry ID of the given webview. Will generate
60 // an ID for the first query.
61 static int GetOrGenerateRulesRegistryID(
62 int embedder_process_id,
63 int web_view_instance_id);
65 // Get the current zoom.
66 double GetZoom() const;
68 // Get the current zoom mode.
69 ui_zoom::ZoomController::ZoomMode GetZoomMode();
71 // Request navigating the guest to the provided |src| URL.
72 void NavigateGuest(const std::string& src, bool force_navigation);
74 // Shows the context menu for the guest.
75 // |items| acts as a filter. This restricts the current context's default
76 // menu items to contain only the items from |items|.
77 // |items| == NULL means no filtering will be applied.
78 void ShowContextMenu(
79 int request_id,
80 const WebViewGuestDelegate::MenuItemVector* items);
82 // Sets the frame name of the guest.
83 void SetName(const std::string& name);
85 // Set the zoom factor.
86 void SetZoom(double zoom_factor);
88 // Set the zoom mode.
89 void SetZoomMode(ui_zoom::ZoomController::ZoomMode zoom_mode);
91 void SetAllowScaling(bool allow);
92 bool allow_scaling() const { return allow_scaling_; }
94 // Sets the transparency of the guest.
95 void SetAllowTransparency(bool allow);
96 bool allow_transparency() const { return allow_transparency_; }
98 // Loads a data URL with a specified base URL and virtual URL.
99 bool LoadDataWithBaseURL(const std::string& data_url,
100 const std::string& base_url,
101 const std::string& virtual_url,
102 std::string* error);
104 // GuestViewBase implementation.
105 bool CanRunInDetachedState() const override;
106 void CreateWebContents(const base::DictionaryValue& create_params,
107 const WebContentsCreatedCallback& callback) override;
108 void DidAttachToEmbedder() override;
109 void DidDropLink(const GURL& url) override;
110 void DidInitialize(const base::DictionaryValue& create_params) override;
111 void GuestViewDidStopLoading() override;
112 void EmbedderFullscreenToggled(bool entered_fullscreen) override;
113 void EmbedderWillBeDestroyed() override;
114 const char* GetAPINamespace() const override;
115 int GetTaskPrefix() const override;
116 void GuestDestroyed() override;
117 void GuestReady() override;
118 void GuestSizeChangedDueToAutoSize(const gfx::Size& old_size,
119 const gfx::Size& new_size) override;
120 void GuestZoomChanged(double old_zoom_level, double new_zoom_level) override;
121 bool IsAutoSizeSupported() const override;
122 bool IsDragAndDropEnabled() const override;
123 void SignalWhenReady(const base::Closure& callback) override;
124 void WillAttachToEmbedder() override;
125 void WillDestroy() override;
127 // WebContentsDelegate implementation.
128 bool AddMessageToConsole(content::WebContents* source,
129 int32 level,
130 const base::string16& message,
131 int32 line_no,
132 const base::string16& source_id) override;
133 void LoadProgressChanged(content::WebContents* source,
134 double progress) override;
135 void CloseContents(content::WebContents* source) override;
136 void FindReply(content::WebContents* source,
137 int request_id,
138 int number_of_matches,
139 const gfx::Rect& selection_rect,
140 int active_match_ordinal,
141 bool final_update) override;
142 bool HandleContextMenu(const content::ContextMenuParams& params) override;
143 void HandleKeyboardEvent(
144 content::WebContents* source,
145 const content::NativeWebKeyboardEvent& event) override;
146 bool PreHandleGestureEvent(content::WebContents* source,
147 const blink::WebGestureEvent& event) override;
148 void RendererResponsive(content::WebContents* source) override;
149 void RendererUnresponsive(content::WebContents* source) override;
150 void RequestMediaAccessPermission(
151 content::WebContents* source,
152 const content::MediaStreamRequest& request,
153 const content::MediaResponseCallback& callback) override;
154 void RequestPointerLockPermission(
155 bool user_gesture,
156 bool last_unlocked_by_target,
157 const base::Callback<void(bool)>& callback) override;
158 bool CheckMediaAccessPermission(content::WebContents* source,
159 const GURL& security_origin,
160 content::MediaStreamType type) override;
161 void CanDownload(content::RenderViewHost* render_view_host,
162 const GURL& url,
163 const std::string& request_method,
164 const base::Callback<void(bool)>& callback) override;
165 content::JavaScriptDialogManager* GetJavaScriptDialogManager(
166 content::WebContents* source) override;
167 void AddNewContents(content::WebContents* source,
168 content::WebContents* new_contents,
169 WindowOpenDisposition disposition,
170 const gfx::Rect& initial_rect,
171 bool user_gesture,
172 bool* was_blocked) override;
173 content::WebContents* OpenURLFromTab(
174 content::WebContents* source,
175 const content::OpenURLParams& params) override;
176 void WebContentsCreated(content::WebContents* source_contents,
177 int opener_render_frame_id,
178 const base::string16& frame_name,
179 const GURL& target_url,
180 content::WebContents* new_contents) override;
181 void EnterFullscreenModeForTab(content::WebContents* web_contents,
182 const GURL& origin) override;
183 void ExitFullscreenModeForTab(content::WebContents* web_contents) override;
184 bool IsFullscreenForTabOrPending(
185 const content::WebContents* web_contents) const override;
187 // NotificationObserver implementation.
188 void Observe(int type,
189 const content::NotificationSource& source,
190 const content::NotificationDetails& details) override;
192 // Begin or continue a find request.
193 void StartFindInternal(
194 const base::string16& search_text,
195 const blink::WebFindOptions& options,
196 scoped_refptr<WebViewInternalFindFunction> find_function);
198 // Conclude a find request to clear highlighting.
199 void StopFindingInternal(content::StopFindAction);
201 // If possible, navigate the guest to |relative_index| entries away from the
202 // current navigation entry. Returns true on success.
203 bool Go(int relative_index);
205 // Reload the guest.
206 void Reload();
208 using PermissionResponseCallback =
209 base::Callback<void(bool /* allow */,
210 const std::string& /* user_input */)>;
211 int RequestPermission(
212 WebViewPermissionType permission_type,
213 const base::DictionaryValue& request_info,
214 const PermissionResponseCallback& callback,
215 bool allowed_by_default);
217 // Requests Geolocation Permission from the embedder.
218 void RequestGeolocationPermission(int bridge_id,
219 const GURL& requesting_frame,
220 bool user_gesture,
221 const base::Callback<void(bool)>& callback);
222 void CancelGeolocationPermissionRequest(int bridge_id);
224 // Called when file system access is requested by the guest content using the
225 // HTML5 file system API in main thread, or a worker thread.
226 // The request is plumbed through the <webview> permission request API. The
227 // request will be:
228 // - Allowed if the embedder explicitly allowed it.
229 // - Denied if the embedder explicitly denied.
230 // - Determined by the guest's content settings if the embedder does not
231 // perform an explicit action.
232 void RequestFileSystemPermission(const GURL& url,
233 bool allowed_by_default,
234 const base::Callback<void(bool)>& callback);
236 // Overrides the user agent for this guest.
237 // This affects subsequent guest navigations.
238 void SetUserAgentOverride(const std::string& user_agent_override);
240 // Stop loading the guest.
241 void Stop();
243 // Kill the guest process.
244 void Terminate();
246 // Clears data in the storage partition of this guest.
248 // Partition data that are newer than |removal_since| will be removed.
249 // |removal_mask| corresponds to bitmask in StoragePartition::RemoveDataMask.
250 bool ClearData(const base::Time remove_since,
251 uint32 removal_mask,
252 const base::Closure& callback);
254 ScriptExecutor* script_executor() { return script_executor_.get(); }
256 scoped_ptr<WebViewGuestDelegate> SetDelegateForTesting(
257 scoped_ptr<WebViewGuestDelegate> delegate) {
258 web_view_guest_delegate_.swap(delegate);
259 return delegate.Pass();
262 private:
263 friend class WebViewPermissionHelper;
265 explicit WebViewGuest(content::WebContents* owner_web_contents);
267 ~WebViewGuest() override;
269 void AttachWebViewHelpers(content::WebContents* contents);
271 void ClearDataInternal(const base::Time remove_since,
272 uint32 removal_mask,
273 const base::Closure& callback);
275 void OnWebViewNewWindowResponse(int new_window_instance_id,
276 bool allow,
277 const std::string& user_input);
279 void OnFullscreenPermissionDecided(bool allowed,
280 const std::string& user_input);
281 bool GuestMadeEmbedderFullscreen() const;
282 void SetFullscreenState(bool is_fullscreen);
284 // WebContentsObserver implementation.
285 void DidCommitProvisionalLoadForFrame(
286 content::RenderFrameHost* render_frame_host,
287 const GURL& url,
288 ui::PageTransition transition_type) override;
289 void DidFailProvisionalLoad(content::RenderFrameHost* render_frame_host,
290 const GURL& validated_url,
291 int error_code,
292 const base::string16& error_description) override;
293 void DidStartProvisionalLoadForFrame(
294 content::RenderFrameHost* render_frame_host,
295 const GURL& validated_url,
296 bool is_error_page,
297 bool is_iframe_srcdoc) override;
298 void DocumentLoadedInFrame(
299 content::RenderFrameHost* render_frame_host) override;
300 void RenderProcessGone(base::TerminationStatus status) override;
301 void UserAgentOverrideSet(const std::string& user_agent) override;
302 void FrameNameChanged(content::RenderFrameHost* render_frame_host,
303 const std::string& name) override;
305 // Informs the embedder of a frame name change.
306 void ReportFrameNameChange(const std::string& name);
308 // Called after the load handler is called in the guest's main frame.
309 void LoadHandlerCalled();
311 // Called when a redirect notification occurs.
312 void LoadRedirect(const GURL& old_url,
313 const GURL& new_url,
314 bool is_top_level);
316 void PushWebViewStateToIOThread();
317 static void RemoveWebViewStateFromIOThread(
318 content::WebContents* web_contents);
320 // Loads the |url| provided. |force_navigation| indicates whether to reload
321 // the content if the provided |url| matches the current page of the guest.
322 void LoadURLWithParams(const GURL& url,
323 const content::Referrer& referrer,
324 ui::PageTransition transition_type,
325 bool force_navigation);
327 void RequestNewWindowPermission(
328 WindowOpenDisposition disposition,
329 const gfx::Rect& initial_bounds,
330 bool user_gesture,
331 content::WebContents* new_contents);
333 // Requests resolution of a potentially relative URL.
334 GURL ResolveURL(const std::string& src);
336 // Notification that a load in the guest resulted in abort. Note that |url|
337 // may be invalid.
338 void LoadAbort(bool is_top_level,
339 const GURL& url,
340 int error_code,
341 const std::string& error_type);
343 // Creates a new guest window owned by this WebViewGuest.
344 void CreateNewGuestWebViewWindow(const content::OpenURLParams& params);
346 void NewGuestWebViewCallback(const content::OpenURLParams& params,
347 content::WebContents* guest_web_contents);
349 bool HandleKeyboardShortcuts(const content::NativeWebKeyboardEvent& event);
351 void ApplyAttributes(const base::DictionaryValue& params);
353 // Identifies the set of rules registries belonging to this guest.
354 int rules_registry_id_;
356 // Handles find requests and replies for the webview find API.
357 WebViewFindHelper find_helper_;
359 ObserverList<ScriptExecutionObserver> script_observers_;
360 scoped_ptr<ScriptExecutor> script_executor_;
362 content::NotificationRegistrar notification_registrar_;
364 // True if the user agent is overridden.
365 bool is_overriding_user_agent_;
367 // Stores the window name of the main frame of the guest.
368 std::string name_;
370 // Stores whether the contents of the guest can be transparent.
371 bool allow_transparency_;
373 // Stores the src URL of the WebView.
374 GURL src_;
376 // Handles the JavaScript dialog requests.
377 JavaScriptDialogHelper javascript_dialog_helper_;
379 // Handles permission requests.
380 scoped_ptr<WebViewPermissionHelper> web_view_permission_helper_;
382 scoped_ptr<WebViewGuestDelegate> web_view_guest_delegate_;
384 // Tracks the name, and target URL of the new window. Once the first
385 // navigation commits, we no longer track this information.
386 struct NewWindowInfo {
387 GURL url;
388 std::string name;
389 bool changed;
390 NewWindowInfo(const GURL& url, const std::string& name) :
391 url(url),
392 name(name),
393 changed(false) {}
396 using PendingWindowMap = std::map<WebViewGuest*, NewWindowInfo>;
397 PendingWindowMap pending_new_windows_;
399 // Determines if this guest accepts pinch-zoom gestures.
400 bool allow_scaling_;
401 bool is_guest_fullscreen_;
402 bool is_embedder_fullscreen_;
403 bool last_fullscreen_permission_was_allowed_by_embedder_;
405 // Tracks whether the webview has a pending zoom from before the first
406 // navigation. This will be equal to 0 when there is no pending zoom.
407 double pending_zoom_factor_;
409 // This is used to ensure pending tasks will not fire after this object is
410 // destroyed.
411 base::WeakPtrFactory<WebViewGuest> weak_ptr_factory_;
413 DISALLOW_COPY_AND_ASSIGN(WebViewGuest);
416 } // namespace extensions
418 #endif // EXTENSIONS_BROWSER_GUEST_VIEW_WEB_VIEW_WEB_VIEW_GUEST_H_