1 // Copyright 2013 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.
7 * @fileoverview Utilities for rendering most visited thumbnails and titles.
10 <include src
="instant_iframe_validation.js">
11 <include src
="window_disposition_util.js">
15 * The different types of events that are logged from the NTP. This enum is
16 * used to transfer information from the NTP javascript to the renderer and is
17 * not used as a UMA enum histogram's logged value.
18 * Note: Keep in sync with common/ntp_logging_events.h
22 var NTP_LOGGING_EVENT_TYPE
= {
23 // The suggestion is coming from the server.
24 NTP_SERVER_SIDE_SUGGESTION
: 0,
25 // The suggestion is coming from the client.
26 NTP_CLIENT_SIDE_SUGGESTION
: 1,
27 // Indicates a tile was rendered, no matter if it's a thumbnail, a gray tile
28 // or an external tile.
30 // The tile uses a local thumbnail image.
31 NTP_THUMBNAIL_TILE
: 3,
32 // Used when no thumbnail is specified and a gray tile with the domain is used
35 // The visuals of that tile are handled externally by the page itself.
37 // There was an error in loading both the thumbnail image and the fallback
38 // (if it was provided), resulting in a grey tile.
39 NTP_THUMBNAIL_ERROR
: 6,
40 // Used a gray tile with the domain as the fallback for a failed thumbnail.
41 NTP_GRAY_TILE_FALLBACK
: 7,
42 // The visuals of that tile's fallback are handled externally.
43 NTP_EXTERNAL_TILE_FALLBACK
: 8,
44 // The user moused over an NTP tile or title.
49 * Type of the impression provider for a generic client-provided suggestion.
53 var CLIENT_PROVIDER_NAME
= 'client';
56 * Type of the impression provider for a generic server-provided suggestion.
60 var SERVER_PROVIDER_NAME
= 'server';
63 * The origin of this request.
66 var DOMAIN_ORIGIN
= '{{ORIGIN}}';
69 * Parses query parameters from Location.
70 * @param {string} location The URL to generate the CSS url for.
71 * @return {Object} Dictionary containing name value pairs for URL.
73 function parseQueryParams(location
) {
74 var params
= Object
.create(null);
75 var query
= location
.search
.substring(1);
76 var vars
= query
.split('&');
77 for (var i
= 0; i
< vars
.length
; i
++) {
78 var pair
= vars
[i
].split('=');
79 var k
= decodeURIComponent(pair
[0]);
81 // Duplicate parameters are not allowed to prevent attackers who can
82 // append things to |location| from getting their parameter values to
83 // override legitimate ones.
84 return Object
.create(null);
86 params
[k
] = decodeURIComponent(pair
[1]);
94 * Creates a new most visited link element.
95 * @param {Object} params URL parameters containing styles for the link.
96 * @param {string} href The destination for the link.
97 * @param {string} title The title for the link.
98 * @param {string|undefined} text The text for the link or none.
99 * @param {string|undefined} direction The text direction.
100 * @param {string|undefined} provider A provider name (max 8 alphanumeric
101 * characters) used for logging. Undefined if suggestion is not coming from
103 * @return {HTMLAnchorElement} A new link element.
105 function createMostVisitedLink(params
, href
, title
, text
, direction
, provider
) {
106 var styles
= getMostVisitedStyles(params
, !!text
);
107 var link
= document
.createElement('a');
108 link
.style
.color
= styles
.color
;
109 link
.style
.fontSize
= styles
.fontSize
+ 'px';
110 if (styles
.fontFamily
)
111 link
.style
.fontFamily
= styles
.fontFamily
;
112 if (styles
.textAlign
)
113 link
.style
.textAlign
= styles
.textAlign
;
114 if (styles
.textFadePos
) {
115 var dir
= /^rtl$/i.test(direction
) ? 'to left' : 'to right';
116 // The fading length in pixels is passed by the caller.
117 var mask
= 'linear-gradient(' + dir
+ ', rgba(0,0,0,1), rgba(0,0,0,1) ' +
118 styles
.textFadePos
+ 'px, rgba(0,0,0,0))';
119 link
.style
.textOverflow
= 'clip';
120 link
.style
.webkitMask
= mask
;
125 link
.target
= '_top';
126 // Include links in the tab order. The tabIndex is necessary for
130 link
.textContent
= text
;
131 link
.addEventListener('mouseover', function() {
132 var ntpApiHandle
= chrome
.embeddedSearch
.newTabPage
;
133 ntpApiHandle
.logEvent(NTP_LOGGING_EVENT_TYPE
.NTP_MOUSEOVER
);
135 link
.addEventListener('focus', function() {
136 window
.parent
.postMessage('linkFocused', DOMAIN_ORIGIN
);
138 link
.addEventListener('blur', function() {
139 window
.parent
.postMessage('linkBlurred', DOMAIN_ORIGIN
);
142 // Webkit's security policy prevents some Most Visited thumbnails from
143 // working (those with schemes different from http and https). Therefore,
144 // navigateContentWindow is being used in order to get all schemes working.
145 var navigateFunction
= function handleNavigation(e
) {
146 var isServerSuggestion
= 'url' in params
;
148 // Ping are only populated for server-side suggestions, never for MV.
149 if (isServerSuggestion
&& params
.ping
) {
150 generatePing(DOMAIN_ORIGIN
+ params
.ping
);
153 var ntpApiHandle
= chrome
.embeddedSearch
.newTabPage
;
154 if ('pos' in params
&& isFinite(params
.pos
)) {
155 ntpApiHandle
.logMostVisitedNavigation(parseInt(params
.pos
, 10),
159 if (!isServerSuggestion
) {
161 ntpApiHandle
.navigateContentWindow(href
, getDispositionFromEvent(e
));
163 // Else follow <a> normally, so transition type would be LINK.
166 link
.addEventListener('click', navigateFunction
);
167 link
.addEventListener('keydown', function(event
) {
168 if (event
.keyCode
== 46 /* DELETE */ ||
169 event
.keyCode
== 8 /* BACKSPACE */) {
170 event
.preventDefault();
171 window
.parent
.postMessage('tileBlacklisted,' + params
.pos
, DOMAIN_ORIGIN
);
172 } else if (event
.keyCode
== 13 /* ENTER */ ||
173 event
.keyCode
== 32 /* SPACE */) {
174 // Event target is the <a> tag. Send a click event on it, which will
175 // trigger the 'click' event registered above.
176 event
.preventDefault();
177 event
.target
.click();
186 * Returns the color to display string with, depending on whether title is
187 * displayed, the current theme, and URL parameters.
188 * @param {Object<string, string>} params URL parameters specifying style.
189 * @param {boolean} isTitle if the style is for the Most Visited Title.
190 * @return {string} The color to use, in "rgba(#,#,#,#)" format.
192 function getTextColor(params
, isTitle
) {
193 // 'RRGGBBAA' color format overrides everything.
194 if ('c' in params
&& params
.c
.match(/^[0-9A-Fa-f]{8}$/)) {
195 // Extract the 4 pairs of hex digits, map to number, then form rgba().
196 var t
= params
.c
.match(/(..)(..)(..)(..)/).slice(1).map(function(s
) {
197 return parseInt(s
, 16);
199 return 'rgba(' + t
[0] + ',' + t
[1] + ',' + t
[2] + ',' + t
[3] / 255 + ')';
202 // For backward compatibility with server-side NTP, look at themes directly
203 // and use param.c for non-title or as fallback.
204 var apiHandle
= chrome
.embeddedSearch
.newTabPage
;
205 var themeInfo
= apiHandle
.themeBackgroundInfo
;
207 if (isTitle
&& themeInfo
&& !themeInfo
.usingDefaultTheme
) {
208 // Read from theme directly
209 c
= convertArrayToRGBAColor(themeInfo
.textColorRgba
) || c
;
210 } else if ('c' in params
) {
211 c
= convertToHexColor(parseInt(params
.c
, 16)) || c
;
218 * Decodes most visited styles from URL parameters.
219 * - c: A hexadecimal number interpreted as a hex color code.
221 * - fs: font-size as a number in pixels.
222 * - ta: text-align property, as a string.
223 * - tf: specifying a text fade starting position, in pixels.
224 * @param {Object<string, string>} params URL parameters specifying style.
225 * @param {boolean} isTitle if the style is for the Most Visited Title.
226 * @return {Object} Styles suitable for CSS interpolation.
228 function getMostVisitedStyles(params
, isTitle
) {
230 color
: getTextColor(params
, isTitle
), // Handles 'c' in params.
234 if ('f' in params
&& /^[-0-9a-zA-Z ,]+$/.test(params
.f
))
235 styles
.fontFamily
= params
.f
;
236 if ('fs' in params
&& isFinite(parseInt(params
.fs
, 10)))
237 styles
.fontSize
= parseInt(params
.fs
, 10);
238 if ('ta' in params
&& /^[-0-9a-zA-Z ,]+$/.test(params
.ta
))
239 styles
.textAlign
= params
.ta
;
240 if ('tf' in params
) {
241 var tf
= parseInt(params
.tf
, 10);
243 styles
.textFadePos
= tf
;
250 * @param {string} location A location containing URL parameters.
251 * @param {function(Object, Object)} fill A function called with styles and
254 function fillMostVisited(location
, fill
) {
255 var params
= parseQueryParams(location
);
256 params
.rid
= parseInt(params
.rid
, 10);
257 if (!isFinite(params
.rid
) && !params
.url
)
259 // Log whether the suggestion was obtained from the server or the client.
260 chrome
.embeddedSearch
.newTabPage
.logEvent(params
.url
?
261 NTP_LOGGING_EVENT_TYPE
.NTP_SERVER_SIDE_SUGGESTION
:
262 NTP_LOGGING_EVENT_TYPE
.NTP_CLIENT_SIDE_SUGGESTION
);
265 // Means that the suggestion data comes from the server. Create data object.
268 thumbnailUrl
: params
.tu
|| '',
269 title
: params
.ti
|| '',
270 direction
: params
.di
|| '',
271 domain
: params
.dom
|| '',
272 provider
: params
.pr
|| SERVER_PROVIDER_NAME
274 // Log the fact that suggestion was obtained from the server.
275 var ntpApiHandle
= chrome
.embeddedSearch
.newTabPage
;
276 ntpApiHandle
.logEvent(NTP_LOGGING_EVENT_TYPE
.NTP_SERVER_SIDE_SUGGESTION
);
278 var apiHandle
= chrome
.embeddedSearch
.searchBox
;
279 data
= apiHandle
.getMostVisitedItemData(params
.rid
);
282 // Allow server-side provider override.
283 data
.provider
= params
.pr
|| CLIENT_PROVIDER_NAME
;
285 if (isFinite(params
.dummy
) && parseInt(params
.dummy
, 10)) {
288 if (/^javascript:/i.test(data
.url
) ||
289 /^javascript:/i.test(data
.thumbnailUrl
) ||
290 !/^[a-z0-9]{0,8}$/i.test(data
.provider
))
293 document
.body
.dir
= data
.direction
;
299 * Sends a POST request to ping url.
300 * @param {string} url URL to be pinged.
302 function generatePing(url
) {
303 if (navigator
.sendBeacon
) {
304 navigator
.sendBeacon(url
);
306 // if sendBeacon is not enabled, we fallback for "a ping".
307 var a
= document
.createElement('a');