util.js revision 731df977c0511bca2206b5f333555b1205ff1f43
1// Copyright (c) 2010 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/**
6 * The global object.
7 * @param {!Object}
8 */
9const global = this;
10
11/**
12 * Alias for document.getElementById.
13 * @param {string} id The ID of the element to find.
14 * @return {HTMLElement} The found element or null if not found.
15 */
16function $(id) {
17  return document.getElementById(id);
18}
19
20/**
21 * Calls chrome.send with a callback and restores the original afterwards.
22 * @param {string} name The name of the message to send.
23 * @param {!Array} params The parameters to send.
24 * @param {string} callbackName The name of the function that the backend calls.
25 * @param {!Function} The function to call.
26 */
27function chromeSend(name, params, callbackName, callback) {
28  var old = global[callbackName];
29  global[callbackName] = function() {
30    // restore
31    global[callbackName] = old;
32
33    var args = Array.prototype.slice.call(arguments);
34    return callback.apply(global, args);
35  };
36  chrome.send(name, params);
37}
38
39
40/**
41 * Generates a CSS url string.
42 * @param {string} s The URL to generate the CSS url for.
43 * @return {string} The CSS url string.
44 */
45function url(s) {
46  // http://www.w3.org/TR/css3-values/#uris
47  // Parentheses, commas, whitespace characters, single quotes (') and double
48  // quotes (") appearing in a URI must be escaped with a backslash
49  var s2 = s.replace(/(\(|\)|\,|\s|\'|\"|\\)/g, '\\$1');
50  // WebKit has a bug when it comes to URLs that end with \
51  // https://bugs.webkit.org/show_bug.cgi?id=28885
52  if (/\\\\$/.test(s2)) {
53    // Add a space to work around the WebKit bug.
54    s2 += ' ';
55  }
56  return 'url("' + s2 + '")';
57}
58
59/**
60 * Parses query parameters from Location.
61 * @param {string} s The URL to generate the CSS url for.
62 * @return {object} Dictionary containing name value pairs for URL
63 */
64function parseQueryParams(location) {
65  var params = {};
66  var query = unescape(location.search.substring(1));
67  var vars = query.split("&");
68  for (var i=0; i < vars.length; i++) {
69    var pair = vars[i].split("=");
70    params[pair[0]] = pair[1];
71  }
72  return params;
73 }
74