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 #include "chrome/browser/extensions/extension_tab_util.h"
7 #include "base/strings/string_number_conversions.h"
8 #include "base/strings/stringprintf.h"
9 #include "chrome/browser/extensions/api/tabs/tabs_constants.h"
10 #include "chrome/browser/extensions/chrome_extension_function.h"
11 #include "chrome/browser/extensions/chrome_extension_function_details.h"
12 #include "chrome/browser/extensions/tab_helper.h"
13 #include "chrome/browser/extensions/window_controller.h"
14 #include "chrome/browser/extensions/window_controller_list.h"
15 #include "chrome/browser/profiles/profile.h"
16 #include "chrome/browser/sessions/session_tab_helper.h"
17 #include "chrome/browser/ui/browser.h"
18 #include "chrome/browser/ui/browser_finder.h"
19 #include "chrome/browser/ui/browser_iterator.h"
20 #include "chrome/browser/ui/browser_window.h"
21 #include "chrome/browser/ui/scoped_tabbed_browser_displayer.h"
22 #include "chrome/browser/ui/singleton_tabs.h"
23 #include "chrome/browser/ui/tab_contents/tab_contents_iterator.h"
24 #include "chrome/browser/ui/tabs/tab_strip_model.h"
25 #include "chrome/browser/ui/tabs/tab_utils.h"
26 #include "chrome/common/extensions/api/tabs.h"
27 #include "chrome/common/url_constants.h"
28 #include "components/url_fixer/url_fixer.h"
29 #include "content/public/browser/favicon_status.h"
30 #include "content/public/browser/navigation_entry.h"
31 #include "content/public/browser/web_contents.h"
32 #include "extensions/browser/app_window/app_window.h"
33 #include "extensions/browser/app_window/app_window_registry.h"
34 #include "extensions/common/constants.h"
35 #include "extensions/common/error_utils.h"
36 #include "extensions/common/extension.h"
37 #include "extensions/common/feature_switch.h"
38 #include "extensions/common/manifest_constants.h"
39 #include "extensions/common/manifest_handlers/incognito_info.h"
40 #include "extensions/common/manifest_handlers/options_page_info.h"
41 #include "extensions/common/permissions/api_permission.h"
42 #include "extensions/common/permissions/permissions_data.h"
45 using content::NavigationEntry
;
46 using content::WebContents
;
48 namespace extensions
{
52 namespace keys
= tabs_constants
;
54 WindowController
* GetAppWindowController(const WebContents
* contents
) {
55 Profile
* profile
= Profile::FromBrowserContext(contents
->GetBrowserContext());
56 AppWindowRegistry
* registry
= AppWindowRegistry::Get(profile
);
59 AppWindow
* app_window
= registry
->GetAppWindowForWebContents(contents
);
62 return WindowControllerList::GetInstance()->FindWindowById(
63 app_window
->session_id().id());
66 // |error_message| can optionally be passed in and will be set with an
67 // appropriate message if the window cannot be found by id.
68 Browser
* GetBrowserInProfileWithId(Profile
* profile
,
70 bool include_incognito
,
71 std::string
* error_message
) {
72 Profile
* incognito_profile
=
73 include_incognito
&& profile
->HasOffTheRecordProfile()
74 ? profile
->GetOffTheRecordProfile()
76 for (chrome::BrowserIterator it
; !it
.done(); it
.Next()) {
77 Browser
* browser
= *it
;
78 if ((browser
->profile() == profile
||
79 browser
->profile() == incognito_profile
) &&
80 ExtensionTabUtil::GetWindowId(browser
) == window_id
&&
87 *error_message
= ErrorUtils::FormatErrorMessage(
88 keys::kWindowNotFoundError
, base::IntToString(window_id
));
93 Browser
* CreateBrowser(ChromeUIThreadExtensionFunction
* function
,
96 content::WebContents
* web_contents
= function
->GetAssociatedWebContents();
97 chrome::HostDesktopType desktop_type
=
98 web_contents
&& web_contents
->GetNativeView()
99 ? chrome::GetHostDesktopTypeForNativeView(
100 web_contents
->GetNativeView())
101 : chrome::GetHostDesktopTypeForNativeView(NULL
);
102 Browser::CreateParams
params(
103 Browser::TYPE_TABBED
, function
->GetProfile(), desktop_type
);
104 Browser
* browser
= new Browser(params
);
105 browser
->window()->Show();
111 ExtensionTabUtil::OpenTabParams::OpenTabParams()
112 : create_browser_if_needed(false) {
115 ExtensionTabUtil::OpenTabParams::~OpenTabParams() {
118 // Opens a new tab for a given extension. Returns NULL and sets |error| if an
120 base::DictionaryValue
* ExtensionTabUtil::OpenTab(
121 ChromeUIThreadExtensionFunction
* function
,
122 const OpenTabParams
& params
,
123 std::string
* error
) {
124 // windowId defaults to "current" window.
125 int window_id
= extension_misc::kCurrentWindowId
;
126 if (params
.window_id
.get())
127 window_id
= *params
.window_id
;
129 Browser
* browser
= GetBrowserFromWindowID(function
, window_id
, error
);
131 if (!params
.create_browser_if_needed
) {
134 browser
= CreateBrowser(function
, window_id
, error
);
139 // Ensure the selected browser is tabbed.
140 if (!browser
->is_type_tabbed() && browser
->IsAttemptingToCloseBrowser())
141 browser
= chrome::FindTabbedBrowser(function
->GetProfile(),
142 function
->include_incognito(),
143 browser
->host_desktop_type());
145 if (!browser
|| !browser
->window()) {
147 *error
= keys::kNoCurrentWindowError
;
151 // TODO(jstritar): Add a constant, chrome.tabs.TAB_ID_ACTIVE, that
152 // represents the active tab.
153 WebContents
* opener
= NULL
;
154 if (params
.opener_tab_id
.get()) {
155 int opener_id
= *params
.opener_tab_id
;
157 if (!ExtensionTabUtil::GetTabById(opener_id
,
158 function
->GetProfile(),
159 function
->include_incognito(),
165 *error
= ErrorUtils::FormatErrorMessage(keys::kTabNotFoundError
,
166 base::IntToString(opener_id
));
172 // TODO(rafaelw): handle setting remaining tab properties:
177 if (params
.url
.get()) {
178 std::string url_string
= *params
.url
;
179 url
= ExtensionTabUtil::ResolvePossiblyRelativeURL(url_string
,
180 function
->extension());
181 if (!url
.is_valid()) {
183 ErrorUtils::FormatErrorMessage(keys::kInvalidUrlError
, url_string
);
187 url
= GURL(chrome::kChromeUINewTabURL
);
190 // Don't let extensions crash the browser or renderers.
191 if (ExtensionTabUtil::IsKillURL(url
)) {
192 *error
= keys::kNoCrashBrowserError
;
196 // Default to foreground for the new tab. The presence of 'active' property
197 // will override this default.
199 if (params
.active
.get())
200 active
= *params
.active
;
202 // Default to not pinning the tab. Setting the 'pinned' property to true
203 // will override this default.
205 if (params
.pinned
.get())
206 pinned
= *params
.pinned
;
208 // We can't load extension URLs into incognito windows unless the extension
209 // uses split mode. Special case to fall back to a tabbed window.
210 if (url
.SchemeIs(kExtensionScheme
) &&
211 !IncognitoInfo::IsSplitMode(function
->extension()) &&
212 browser
->profile()->IsOffTheRecord()) {
213 Profile
* profile
= browser
->profile()->GetOriginalProfile();
214 chrome::HostDesktopType desktop_type
= browser
->host_desktop_type();
216 browser
= chrome::FindTabbedBrowser(profile
, false, desktop_type
);
218 browser
= new Browser(
219 Browser::CreateParams(Browser::TYPE_TABBED
, profile
, desktop_type
));
220 browser
->window()->Show();
224 // If index is specified, honor the value, but keep it bound to
225 // -1 <= index <= tab_strip->count() where -1 invokes the default behavior.
227 if (params
.index
.get())
228 index
= *params
.index
;
230 TabStripModel
* tab_strip
= browser
->tab_strip_model();
232 index
= std::min(std::max(index
, -1), tab_strip
->count());
234 int add_types
= active
? TabStripModel::ADD_ACTIVE
: TabStripModel::ADD_NONE
;
235 add_types
|= TabStripModel::ADD_FORCE_INDEX
;
237 add_types
|= TabStripModel::ADD_PINNED
;
238 chrome::NavigateParams
navigate_params(
239 browser
, url
, ui::PAGE_TRANSITION_LINK
);
240 navigate_params
.disposition
=
241 active
? NEW_FOREGROUND_TAB
: NEW_BACKGROUND_TAB
;
242 navigate_params
.tabstrip_index
= index
;
243 navigate_params
.tabstrip_add_types
= add_types
;
244 chrome::Navigate(&navigate_params
);
246 // The tab may have been created in a different window, so make sure we look
247 // at the right tab strip.
248 tab_strip
= navigate_params
.browser
->tab_strip_model();
250 tab_strip
->GetIndexOfWebContents(navigate_params
.target_contents
);
252 tab_strip
->SetOpenerOfWebContentsAt(new_index
, opener
);
255 navigate_params
.target_contents
->SetInitialFocus();
257 // Return data about the newly created tab.
258 return ExtensionTabUtil::CreateTabValue(navigate_params
.target_contents
,
261 function
->extension());
264 Browser
* ExtensionTabUtil::GetBrowserFromWindowID(
265 ChromeUIThreadExtensionFunction
* function
,
267 std::string
* error
) {
268 if (window_id
== extension_misc::kCurrentWindowId
) {
269 Browser
* result
= function
->GetCurrentBrowser();
270 if (!result
|| !result
->window()) {
272 *error
= keys::kNoCurrentWindowError
;
277 return GetBrowserInProfileWithId(function
->GetProfile(),
279 function
->include_incognito(),
284 Browser
* ExtensionTabUtil::GetBrowserFromWindowID(
285 const ChromeExtensionFunctionDetails
& details
,
287 std::string
* error
) {
288 if (window_id
== extension_misc::kCurrentWindowId
) {
289 Browser
* result
= details
.GetCurrentBrowser();
290 if (!result
|| !result
->window()) {
292 *error
= keys::kNoCurrentWindowError
;
297 return GetBrowserInProfileWithId(details
.GetProfile(),
299 details
.function()->include_incognito(),
304 int ExtensionTabUtil::GetWindowId(const Browser
* browser
) {
305 return browser
->session_id().id();
308 int ExtensionTabUtil::GetWindowIdOfTabStripModel(
309 const TabStripModel
* tab_strip_model
) {
310 for (chrome::BrowserIterator it
; !it
.done(); it
.Next()) {
311 if (it
->tab_strip_model() == tab_strip_model
)
312 return GetWindowId(*it
);
317 int ExtensionTabUtil::GetTabId(const WebContents
* web_contents
) {
318 Browser
* browser
= chrome::FindBrowserWithWebContents(web_contents
);
319 if (browser
&& !ExtensionTabUtil::BrowserSupportsTabs(browser
))
321 return SessionTabHelper::IdForTab(web_contents
);
324 std::string
ExtensionTabUtil::GetTabStatusText(bool is_loading
) {
325 return is_loading
? keys::kStatusValueLoading
: keys::kStatusValueComplete
;
328 int ExtensionTabUtil::GetWindowIdOfTab(const WebContents
* web_contents
) {
329 return SessionTabHelper::IdForWindowContainingTab(web_contents
);
332 base::DictionaryValue
* ExtensionTabUtil::CreateTabValue(
333 WebContents
* contents
,
334 TabStripModel
* tab_strip
,
336 const Extension
* extension
) {
337 // If we have a matching AppWindow with a controller, get the tab value
338 // from its controller instead.
339 WindowController
* controller
= GetAppWindowController(contents
);
341 (!extension
|| controller
->IsVisibleToExtension(extension
))) {
342 return controller
->CreateTabValue(extension
, tab_index
);
344 base::DictionaryValue
* result
=
345 CreateTabValue(contents
, tab_strip
, tab_index
);
346 ScrubTabValueForExtension(contents
, extension
, result
);
350 base::ListValue
* ExtensionTabUtil::CreateTabList(
351 const Browser
* browser
,
352 const Extension
* extension
) {
353 base::ListValue
* tab_list
= new base::ListValue();
354 TabStripModel
* tab_strip
= browser
->tab_strip_model();
355 for (int i
= 0; i
< tab_strip
->count(); ++i
) {
356 tab_list
->Append(CreateTabValue(tab_strip
->GetWebContentsAt(i
),
365 base::DictionaryValue
* ExtensionTabUtil::CreateTabValue(
366 WebContents
* contents
,
367 TabStripModel
* tab_strip
,
369 // If we have a matching AppWindow with a controller, get the tab value
370 // from its controller instead.
371 WindowController
* controller
= GetAppWindowController(contents
);
373 return controller
->CreateTabValue(NULL
, tab_index
);
376 ExtensionTabUtil::GetTabStripModel(contents
, &tab_strip
, &tab_index
);
378 base::DictionaryValue
* result
= new base::DictionaryValue();
379 bool is_loading
= contents
->IsLoading();
380 result
->SetInteger(keys::kIdKey
, GetTabId(contents
));
381 result
->SetInteger(keys::kIndexKey
, tab_index
);
382 result
->SetInteger(keys::kWindowIdKey
, GetWindowIdOfTab(contents
));
383 result
->SetString(keys::kStatusKey
, GetTabStatusText(is_loading
));
384 result
->SetBoolean(keys::kActiveKey
,
385 tab_strip
&& tab_index
== tab_strip
->active_index());
386 result
->SetBoolean(keys::kSelectedKey
,
387 tab_strip
&& tab_index
== tab_strip
->active_index());
388 result
->SetBoolean(keys::kHighlightedKey
,
389 tab_strip
&& tab_strip
->IsTabSelected(tab_index
));
390 result
->SetBoolean(keys::kPinnedKey
,
391 tab_strip
&& tab_strip
->IsTabPinned(tab_index
));
392 result
->SetBoolean(keys::kAudibleKey
,
393 tab_strip
&& chrome::IsPlayingAudio(contents
));
394 result
->SetBoolean(keys::kMutedKey
,
395 tab_strip
&& chrome::IsTabAudioMuted(contents
));
396 result
->SetString(keys::kMutedCauseKey
,
397 chrome::GetTabAudioMutedCause(contents
));
398 result
->SetBoolean(keys::kIncognitoKey
,
399 contents
->GetBrowserContext()->IsOffTheRecord());
400 result
->SetInteger(keys::kWidthKey
,
401 contents
->GetContainerBounds().size().width());
402 result
->SetInteger(keys::kHeightKey
,
403 contents
->GetContainerBounds().size().height());
405 // Privacy-sensitive fields: these should be stripped off by
406 // ScrubTabValueForExtension if the extension should not see them.
407 result
->SetString(keys::kUrlKey
, contents
->GetURL().spec());
408 result
->SetString(keys::kTitleKey
, contents
->GetTitle());
410 NavigationEntry
* entry
= contents
->GetController().GetVisibleEntry();
411 if (entry
&& entry
->GetFavicon().valid
)
412 result
->SetString(keys::kFaviconUrlKey
, entry
->GetFavicon().url
.spec());
416 WebContents
* opener
= tab_strip
->GetOpenerOfWebContentsAt(tab_index
);
418 result
->SetInteger(keys::kOpenerTabIdKey
, GetTabId(opener
));
424 void ExtensionTabUtil::ScrubTabValueForExtension(
425 WebContents
* contents
,
426 const Extension
* extension
,
427 base::DictionaryValue
* tab_info
) {
428 bool has_permission
= extension
&&
429 extension
->permissions_data()->HasAPIPermissionForTab(
430 GetTabId(contents
), APIPermission::kTab
);
432 if (!has_permission
) {
433 tab_info
->Remove(keys::kUrlKey
, NULL
);
434 tab_info
->Remove(keys::kTitleKey
, NULL
);
435 tab_info
->Remove(keys::kFaviconUrlKey
, NULL
);
439 void ExtensionTabUtil::ScrubTabForExtension(const Extension
* extension
,
440 api::tabs::Tab
* tab
) {
441 bool has_permission
=
443 extension
->permissions_data()->HasAPIPermission(APIPermission::kTab
);
445 if (!has_permission
) {
448 tab
->fav_icon_url
.reset();
452 bool ExtensionTabUtil::GetTabStripModel(const WebContents
* web_contents
,
453 TabStripModel
** tab_strip_model
,
455 DCHECK(web_contents
);
456 DCHECK(tab_strip_model
);
459 for (chrome::BrowserIterator it
; !it
.done(); it
.Next()) {
460 TabStripModel
* tab_strip
= it
->tab_strip_model();
461 int index
= tab_strip
->GetIndexOfWebContents(web_contents
);
463 *tab_strip_model
= tab_strip
;
472 bool ExtensionTabUtil::GetDefaultTab(Browser
* browser
,
473 WebContents
** contents
,
478 *contents
= browser
->tab_strip_model()->GetActiveWebContents();
481 *tab_id
= GetTabId(*contents
);
488 bool ExtensionTabUtil::GetTabById(int tab_id
,
489 content::BrowserContext
* browser_context
,
490 bool include_incognito
,
492 TabStripModel
** tab_strip
,
493 WebContents
** contents
,
495 if (tab_id
== api::tabs::TAB_ID_NONE
)
497 Profile
* profile
= Profile::FromBrowserContext(browser_context
);
498 Profile
* incognito_profile
=
499 include_incognito
&& profile
->HasOffTheRecordProfile() ?
500 profile
->GetOffTheRecordProfile() : NULL
;
501 for (chrome::BrowserIterator it
; !it
.done(); it
.Next()) {
502 Browser
* target_browser
= *it
;
503 if (target_browser
->profile() == profile
||
504 target_browser
->profile() == incognito_profile
) {
505 TabStripModel
* target_tab_strip
= target_browser
->tab_strip_model();
506 for (int i
= 0; i
< target_tab_strip
->count(); ++i
) {
507 WebContents
* target_contents
= target_tab_strip
->GetWebContentsAt(i
);
508 if (SessionTabHelper::IdForTab(target_contents
) == tab_id
) {
510 *browser
= target_browser
;
512 *tab_strip
= target_tab_strip
;
514 *contents
= target_contents
;
525 GURL
ExtensionTabUtil::ResolvePossiblyRelativeURL(const std::string
& url_string
,
526 const Extension
* extension
) {
527 GURL url
= GURL(url_string
);
529 url
= extension
->GetResourceURL(url_string
);
534 bool ExtensionTabUtil::IsKillURL(const GURL
& url
) {
535 static const char* kill_hosts
[] = {
536 chrome::kChromeUICrashHost
,
537 chrome::kChromeUIHangUIHost
,
538 chrome::kChromeUIKillHost
,
539 chrome::kChromeUIQuitHost
,
540 chrome::kChromeUIRestartHost
,
541 content::kChromeUIBrowserCrashHost
,
544 // Check a fixed-up URL, to normalize the scheme and parse hosts correctly.
546 url_fixer::FixupURL(url
.possibly_invalid_spec(), std::string());
547 if (!fixed_url
.SchemeIs(content::kChromeUIScheme
))
550 for (size_t i
= 0; i
< arraysize(kill_hosts
); ++i
) {
551 if (fixed_url
.host() == kill_hosts
[i
])
558 void ExtensionTabUtil::CreateTab(WebContents
* web_contents
,
559 const std::string
& extension_id
,
560 WindowOpenDisposition disposition
,
561 const gfx::Rect
& initial_rect
,
564 Profile::FromBrowserContext(web_contents
->GetBrowserContext());
565 chrome::HostDesktopType active_desktop
= chrome::GetActiveDesktop();
566 Browser
* browser
= chrome::FindTabbedBrowser(profile
, false, active_desktop
);
567 const bool browser_created
= !browser
;
569 browser
= new Browser(Browser::CreateParams(profile
, active_desktop
));
570 chrome::NavigateParams
params(browser
, web_contents
);
572 // The extension_app_id parameter ends up as app_name in the Browser
573 // which causes the Browser to return true for is_app(). This affects
574 // among other things, whether the location bar gets displayed.
575 // TODO(mpcomplete): This seems wrong. What if the extension content is hosted
577 if (disposition
== NEW_POPUP
)
578 params
.extension_app_id
= extension_id
;
580 params
.disposition
= disposition
;
581 params
.window_bounds
= initial_rect
;
582 params
.window_action
= chrome::NavigateParams::SHOW_WINDOW
;
583 params
.user_gesture
= user_gesture
;
584 chrome::Navigate(¶ms
);
586 // Close the browser if chrome::Navigate created a new one.
587 if (browser_created
&& (browser
!= params
.browser
))
588 browser
->window()->Close();
592 void ExtensionTabUtil::ForEachTab(
593 const base::Callback
<void(WebContents
*)>& callback
) {
594 for (TabContentsIterator iterator
; !iterator
.done(); iterator
.Next())
595 callback
.Run(*iterator
);
599 WindowController
* ExtensionTabUtil::GetWindowControllerOfTab(
600 const WebContents
* web_contents
) {
601 Browser
* browser
= chrome::FindBrowserWithWebContents(web_contents
);
603 return browser
->extension_window_controller();
608 bool ExtensionTabUtil::OpenOptionsPage(const Extension
* extension
,
610 if (!OptionsPageInfo::HasOptionsPage(extension
))
613 // Force the options page to open in non-OTR window, because it won't be
614 // able to save settings from OTR.
615 scoped_ptr
<chrome::ScopedTabbedBrowserDisplayer
> displayer
;
616 if (browser
->profile()->IsOffTheRecord()) {
617 displayer
.reset(new chrome::ScopedTabbedBrowserDisplayer(
618 browser
->profile()->GetOriginalProfile(),
619 browser
->host_desktop_type()));
620 browser
= displayer
->browser();
623 GURL url_to_navigate
;
624 if (OptionsPageInfo::ShouldOpenInTab(extension
)) {
625 // Options page tab is simply e.g. chrome-extension://.../options.html.
626 url_to_navigate
= OptionsPageInfo::GetOptionsPage(extension
);
628 // Options page tab is Extension settings pointed at that Extension's ID,
629 // e.g. chrome://extensions?options=...
630 url_to_navigate
= GURL(chrome::kChromeUIExtensionsURL
);
631 GURL::Replacements replacements
;
633 base::StringPrintf("options=%s", extension
->id().c_str());
634 replacements
.SetQueryStr(query
);
635 url_to_navigate
= url_to_navigate
.ReplaceComponents(replacements
);
638 chrome::NavigateParams
params(
639 chrome::GetSingletonTabNavigateParams(browser
, url_to_navigate
));
640 params
.path_behavior
= chrome::NavigateParams::IGNORE_AND_NAVIGATE
;
641 params
.url
= url_to_navigate
;
642 chrome::ShowSingletonTabOverwritingNTP(browser
, params
);
647 bool ExtensionTabUtil::BrowserSupportsTabs(Browser
* browser
) {
648 return browser
&& browser
->tab_strip_model() && !browser
->is_devtools();
651 } // namespace extensions