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/common/extensions/api/tabs.h"
26 #include "chrome/common/url_constants.h"
27 #include "components/url_fixer/url_fixer.h"
28 #include "content/public/browser/favicon_status.h"
29 #include "content/public/browser/navigation_entry.h"
30 #include "content/public/browser/web_contents.h"
31 #include "extensions/browser/app_window/app_window.h"
32 #include "extensions/browser/app_window/app_window_registry.h"
33 #include "extensions/common/constants.h"
34 #include "extensions/common/error_utils.h"
35 #include "extensions/common/extension.h"
36 #include "extensions/common/feature_switch.h"
37 #include "extensions/common/manifest_constants.h"
38 #include "extensions/common/manifest_handlers/incognito_info.h"
39 #include "extensions/common/manifest_handlers/options_page_info.h"
40 #include "extensions/common/permissions/api_permission.h"
41 #include "extensions/common/permissions/permissions_data.h"
44 using content::NavigationEntry;
45 using content::WebContents;
47 namespace extensions {
51 namespace keys = tabs_constants;
53 WindowController* GetAppWindowController(const WebContents* contents) {
54 Profile* profile = Profile::FromBrowserContext(contents->GetBrowserContext());
55 AppWindowRegistry* registry = AppWindowRegistry::Get(profile);
58 AppWindow* app_window =
59 registry->GetAppWindowForRenderViewHost(contents->GetRenderViewHost());
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();
98 DCHECK(web_contents->GetNativeView());
99 DCHECK(!chrome::FindBrowserWithWebContents(web_contents));
101 chrome::HostDesktopType desktop_type =
102 chrome::GetHostDesktopTypeForNativeView(web_contents->GetNativeView());
103 Browser::CreateParams params(
104 Browser::TYPE_TABBED, function->GetProfile(), desktop_type);
105 Browser* browser = new Browser(params);
106 browser->window()->Show();
112 ExtensionTabUtil::OpenTabParams::OpenTabParams()
113 : create_browser_if_needed(false) {
116 ExtensionTabUtil::OpenTabParams::~OpenTabParams() {
119 // Opens a new tab for a given extension. Returns NULL and sets |error| if an
121 base::DictionaryValue* ExtensionTabUtil::OpenTab(
122 ChromeUIThreadExtensionFunction* function,
123 const OpenTabParams& params,
124 std::string* error) {
125 // windowId defaults to "current" window.
126 int window_id = extension_misc::kCurrentWindowId;
127 if (params.window_id.get())
128 window_id = *params.window_id;
130 Browser* browser = GetBrowserFromWindowID(function, window_id, error);
132 if (!params.create_browser_if_needed) {
135 browser = CreateBrowser(function, window_id, error);
140 // Ensure the selected browser is tabbed.
141 if (!browser->is_type_tabbed() && browser->IsAttemptingToCloseBrowser())
142 browser = chrome::FindTabbedBrowser(function->GetProfile(),
143 function->include_incognito(),
144 browser->host_desktop_type());
146 if (!browser || !browser->window()) {
147 // TODO(rpaquay): Error message?
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(),
164 // TODO(rpaquay): Error message?
169 // TODO(rafaelw): handle setting remaining tab properties:
174 if (params.url.get()) {
175 std::string url_string= *params.url;
176 url = ExtensionTabUtil::ResolvePossiblyRelativeURL(url_string,
177 function->extension());
178 if (!url.is_valid()) {
180 ErrorUtils::FormatErrorMessage(keys::kInvalidUrlError, url_string);
184 url = GURL(chrome::kChromeUINewTabURL);
187 // Don't let extensions crash the browser or renderers.
188 if (ExtensionTabUtil::IsCrashURL(url)) {
189 *error = keys::kNoCrashBrowserError;
193 // Default to foreground for the new tab. The presence of 'active' property
194 // will override this default.
196 if (params.active.get())
197 active = *params.active;
199 // Default to not pinning the tab. Setting the 'pinned' property to true
200 // will override this default.
202 if (params.pinned.get())
203 pinned = *params.pinned;
205 // We can't load extension URLs into incognito windows unless the extension
206 // uses split mode. Special case to fall back to a tabbed window.
207 if (url.SchemeIs(kExtensionScheme) &&
208 !IncognitoInfo::IsSplitMode(function->extension()) &&
209 browser->profile()->IsOffTheRecord()) {
210 Profile* profile = browser->profile()->GetOriginalProfile();
211 chrome::HostDesktopType desktop_type = browser->host_desktop_type();
213 browser = chrome::FindTabbedBrowser(profile, false, desktop_type);
215 browser = new Browser(
216 Browser::CreateParams(Browser::TYPE_TABBED, profile, desktop_type));
217 browser->window()->Show();
221 // If index is specified, honor the value, but keep it bound to
222 // -1 <= index <= tab_strip->count() where -1 invokes the default behavior.
224 if (params.index.get())
225 index = *params.index;
227 TabStripModel* tab_strip = browser->tab_strip_model();
229 index = std::min(std::max(index, -1), tab_strip->count());
231 int add_types = active ? TabStripModel::ADD_ACTIVE : TabStripModel::ADD_NONE;
232 add_types |= TabStripModel::ADD_FORCE_INDEX;
234 add_types |= TabStripModel::ADD_PINNED;
235 chrome::NavigateParams navigate_params(
236 browser, url, ui::PAGE_TRANSITION_LINK);
237 navigate_params.disposition =
238 active ? NEW_FOREGROUND_TAB : NEW_BACKGROUND_TAB;
239 navigate_params.tabstrip_index = index;
240 navigate_params.tabstrip_add_types = add_types;
241 chrome::Navigate(&navigate_params);
243 // The tab may have been created in a different window, so make sure we look
244 // at the right tab strip.
245 tab_strip = navigate_params.browser->tab_strip_model();
247 tab_strip->GetIndexOfWebContents(navigate_params.target_contents);
249 tab_strip->SetOpenerOfWebContentsAt(new_index, opener);
252 navigate_params.target_contents->SetInitialFocus();
254 // Return data about the newly created tab.
255 return ExtensionTabUtil::CreateTabValue(navigate_params.target_contents,
258 function->extension());
261 Browser* ExtensionTabUtil::GetBrowserFromWindowID(
262 ChromeUIThreadExtensionFunction* function,
264 std::string* error) {
265 if (window_id == extension_misc::kCurrentWindowId) {
266 Browser* result = function->GetCurrentBrowser();
267 if (!result || !result->window()) {
269 *error = keys::kNoCurrentWindowError;
274 return GetBrowserInProfileWithId(function->GetProfile(),
276 function->include_incognito(),
281 Browser* ExtensionTabUtil::GetBrowserFromWindowID(
282 const ChromeExtensionFunctionDetails& details,
284 std::string* error) {
285 if (window_id == extension_misc::kCurrentWindowId) {
286 Browser* result = details.GetCurrentBrowser();
287 if (!result || !result->window()) {
289 *error = keys::kNoCurrentWindowError;
294 return GetBrowserInProfileWithId(details.GetProfile(),
296 details.function()->include_incognito(),
301 int ExtensionTabUtil::GetWindowId(const Browser* browser) {
302 return browser->session_id().id();
305 int ExtensionTabUtil::GetWindowIdOfTabStripModel(
306 const TabStripModel* tab_strip_model) {
307 for (chrome::BrowserIterator it; !it.done(); it.Next()) {
308 if (it->tab_strip_model() == tab_strip_model)
309 return GetWindowId(*it);
314 int ExtensionTabUtil::GetTabId(const WebContents* web_contents) {
315 return SessionTabHelper::IdForTab(web_contents);
318 std::string ExtensionTabUtil::GetTabStatusText(bool is_loading) {
319 return is_loading ? keys::kStatusValueLoading : keys::kStatusValueComplete;
322 int ExtensionTabUtil::GetWindowIdOfTab(const WebContents* web_contents) {
323 return SessionTabHelper::IdForWindowContainingTab(web_contents);
326 base::DictionaryValue* ExtensionTabUtil::CreateTabValue(
327 WebContents* contents,
328 TabStripModel* tab_strip,
330 const Extension* extension) {
331 // If we have a matching AppWindow with a controller, get the tab value
332 // from its controller instead.
333 WindowController* controller = GetAppWindowController(contents);
335 (!extension || controller->IsVisibleToExtension(extension))) {
336 return controller->CreateTabValue(extension, tab_index);
338 base::DictionaryValue* result =
339 CreateTabValue(contents, tab_strip, tab_index);
340 ScrubTabValueForExtension(contents, extension, result);
344 base::ListValue* ExtensionTabUtil::CreateTabList(
345 const Browser* browser,
346 const Extension* extension) {
347 base::ListValue* tab_list = new base::ListValue();
348 TabStripModel* tab_strip = browser->tab_strip_model();
349 for (int i = 0; i < tab_strip->count(); ++i) {
350 tab_list->Append(CreateTabValue(tab_strip->GetWebContentsAt(i),
359 base::DictionaryValue* ExtensionTabUtil::CreateTabValue(
360 WebContents* contents,
361 TabStripModel* tab_strip,
363 // If we have a matching AppWindow with a controller, get the tab value
364 // from its controller instead.
365 WindowController* controller = GetAppWindowController(contents);
367 return controller->CreateTabValue(NULL, tab_index);
370 ExtensionTabUtil::GetTabStripModel(contents, &tab_strip, &tab_index);
372 base::DictionaryValue* result = new base::DictionaryValue();
373 bool is_loading = contents->IsLoading();
374 result->SetInteger(keys::kIdKey, GetTabId(contents));
375 result->SetInteger(keys::kIndexKey, tab_index);
376 result->SetInteger(keys::kWindowIdKey, GetWindowIdOfTab(contents));
377 result->SetString(keys::kStatusKey, GetTabStatusText(is_loading));
378 result->SetBoolean(keys::kActiveKey,
379 tab_strip && tab_index == tab_strip->active_index());
380 result->SetBoolean(keys::kSelectedKey,
381 tab_strip && tab_index == tab_strip->active_index());
382 result->SetBoolean(keys::kHighlightedKey,
383 tab_strip && tab_strip->IsTabSelected(tab_index));
384 result->SetBoolean(keys::kPinnedKey,
385 tab_strip && tab_strip->IsTabPinned(tab_index));
386 result->SetBoolean(keys::kIncognitoKey,
387 contents->GetBrowserContext()->IsOffTheRecord());
388 result->SetInteger(keys::kWidthKey,
389 contents->GetContainerBounds().size().width());
390 result->SetInteger(keys::kHeightKey,
391 contents->GetContainerBounds().size().height());
393 // Privacy-sensitive fields: these should be stripped off by
394 // ScrubTabValueForExtension if the extension should not see them.
395 result->SetString(keys::kUrlKey, contents->GetURL().spec());
396 result->SetString(keys::kTitleKey, contents->GetTitle());
398 NavigationEntry* entry = contents->GetController().GetVisibleEntry();
399 if (entry && entry->GetFavicon().valid)
400 result->SetString(keys::kFaviconUrlKey, entry->GetFavicon().url.spec());
404 WebContents* opener = tab_strip->GetOpenerOfWebContentsAt(tab_index);
406 result->SetInteger(keys::kOpenerTabIdKey, GetTabId(opener));
412 void ExtensionTabUtil::ScrubTabValueForExtension(
413 WebContents* contents,
414 const Extension* extension,
415 base::DictionaryValue* tab_info) {
416 bool has_permission = extension &&
417 extension->permissions_data()->HasAPIPermissionForTab(
418 GetTabId(contents), APIPermission::kTab);
420 if (!has_permission) {
421 tab_info->Remove(keys::kUrlKey, NULL);
422 tab_info->Remove(keys::kTitleKey, NULL);
423 tab_info->Remove(keys::kFaviconUrlKey, NULL);
427 void ExtensionTabUtil::ScrubTabForExtension(const Extension* extension,
428 api::tabs::Tab* tab) {
429 bool has_permission =
431 extension->permissions_data()->HasAPIPermission(APIPermission::kTab);
433 if (!has_permission) {
436 tab->fav_icon_url.reset();
440 bool ExtensionTabUtil::GetTabStripModel(const WebContents* web_contents,
441 TabStripModel** tab_strip_model,
443 DCHECK(web_contents);
444 DCHECK(tab_strip_model);
447 for (chrome::BrowserIterator it; !it.done(); it.Next()) {
448 TabStripModel* tab_strip = it->tab_strip_model();
449 int index = tab_strip->GetIndexOfWebContents(web_contents);
451 *tab_strip_model = tab_strip;
460 bool ExtensionTabUtil::GetDefaultTab(Browser* browser,
461 WebContents** contents,
466 *contents = browser->tab_strip_model()->GetActiveWebContents();
469 *tab_id = GetTabId(*contents);
476 bool ExtensionTabUtil::GetTabById(int tab_id,
477 content::BrowserContext* browser_context,
478 bool include_incognito,
480 TabStripModel** tab_strip,
481 WebContents** contents,
483 Profile* profile = Profile::FromBrowserContext(browser_context);
484 Profile* incognito_profile =
485 include_incognito && profile->HasOffTheRecordProfile() ?
486 profile->GetOffTheRecordProfile() : NULL;
487 for (chrome::BrowserIterator it; !it.done(); it.Next()) {
488 Browser* target_browser = *it;
489 if (target_browser->profile() == profile ||
490 target_browser->profile() == incognito_profile) {
491 TabStripModel* target_tab_strip = target_browser->tab_strip_model();
492 for (int i = 0; i < target_tab_strip->count(); ++i) {
493 WebContents* target_contents = target_tab_strip->GetWebContentsAt(i);
494 if (SessionTabHelper::IdForTab(target_contents) == tab_id) {
496 *browser = target_browser;
498 *tab_strip = target_tab_strip;
500 *contents = target_contents;
511 GURL ExtensionTabUtil::ResolvePossiblyRelativeURL(const std::string& url_string,
512 const Extension* extension) {
513 GURL url = GURL(url_string);
515 url = extension->GetResourceURL(url_string);
520 bool ExtensionTabUtil::IsCrashURL(const GURL& url) {
521 // Check a fixed-up URL, to normalize the scheme and parse hosts correctly.
523 url_fixer::FixupURL(url.possibly_invalid_spec(), std::string());
524 return (fixed_url.SchemeIs(content::kChromeUIScheme) &&
525 (fixed_url.host() == content::kChromeUIBrowserCrashHost ||
526 fixed_url.host() == chrome::kChromeUICrashHost));
529 void ExtensionTabUtil::CreateTab(WebContents* web_contents,
530 const std::string& extension_id,
531 WindowOpenDisposition disposition,
532 const gfx::Rect& initial_pos,
535 Profile::FromBrowserContext(web_contents->GetBrowserContext());
536 chrome::HostDesktopType active_desktop = chrome::GetActiveDesktop();
537 Browser* browser = chrome::FindTabbedBrowser(profile, false, active_desktop);
538 const bool browser_created = !browser;
540 browser = new Browser(Browser::CreateParams(profile, active_desktop));
541 chrome::NavigateParams params(browser, web_contents);
543 // The extension_app_id parameter ends up as app_name in the Browser
544 // which causes the Browser to return true for is_app(). This affects
545 // among other things, whether the location bar gets displayed.
546 // TODO(mpcomplete): This seems wrong. What if the extension content is hosted
548 if (disposition == NEW_POPUP)
549 params.extension_app_id = extension_id;
551 params.disposition = disposition;
552 params.window_bounds = initial_pos;
553 params.window_action = chrome::NavigateParams::SHOW_WINDOW;
554 params.user_gesture = user_gesture;
555 chrome::Navigate(¶ms);
557 // Close the browser if chrome::Navigate created a new one.
558 if (browser_created && (browser != params.browser))
559 browser->window()->Close();
563 void ExtensionTabUtil::ForEachTab(
564 const base::Callback<void(WebContents*)>& callback) {
565 for (TabContentsIterator iterator; !iterator.done(); iterator.Next())
566 callback.Run(*iterator);
570 WindowController* ExtensionTabUtil::GetWindowControllerOfTab(
571 const WebContents* web_contents) {
572 Browser* browser = chrome::FindBrowserWithWebContents(web_contents);
574 return browser->extension_window_controller();
579 void ExtensionTabUtil::OpenOptionsPage(const Extension* extension,
581 DCHECK(OptionsPageInfo::HasOptionsPage(extension));
583 // Force the options page to open in non-OTR window, because it won't be
584 // able to save settings from OTR.
585 scoped_ptr<chrome::ScopedTabbedBrowserDisplayer> displayer;
586 if (browser->profile()->IsOffTheRecord()) {
587 displayer.reset(new chrome::ScopedTabbedBrowserDisplayer(
588 browser->profile()->GetOriginalProfile(),
589 browser->host_desktop_type()));
590 browser = displayer->browser();
593 if (!OptionsPageInfo::ShouldOpenInTab(extension)) {
594 // If we should embed the options page for this extension, open
595 // chrome://extensions in a new tab and show the extension options in an
597 chrome::NavigateParams params(chrome::GetSingletonTabNavigateParams(
598 browser, GURL(chrome::kChromeUIExtensionsURL)));
599 params.path_behavior = chrome::NavigateParams::IGNORE_AND_NAVIGATE;
601 GURL::Replacements replacements;
603 base::StringPrintf("options=%s", extension->id().c_str());
604 replacements.SetQueryStr(query);
605 params.url = params.url.ReplaceComponents(replacements);
607 chrome::ShowSingletonTabOverwritingNTP(browser, params);
609 // Otherwise open a new tab with the extension's options page
610 content::OpenURLParams params(OptionsPageInfo::GetOptionsPage(extension),
613 ui::PAGE_TRANSITION_LINK,
615 browser->OpenURL(params);
616 browser->window()->Show();
617 WebContents* web_contents =
618 browser->tab_strip_model()->GetActiveWebContents();
619 web_contents->GetDelegate()->ActivateContents(web_contents);
623 } // namespace extensions