closure_preinit.js revision cedac228d2dd51db4b79ea1e72c7f249408ee061
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. 4 5/** 6 * @fileoverview Code to execute before Closure's base.js. 7 * 8 */ 9 10/** 11 * Tell Closure to load JavaScript code from the extension root directory. 12 * @type {boolean} 13 */ 14window.CLOSURE_BASE_PATH = chrome.extension.getURL('/closure/'); 15 16/** 17 * Tell Closure not to load deps.js; it's included by manifest.json already. 18 * @type {boolean} 19 */ 20window.CLOSURE_NO_DEPS = true; 21 22/** 23 * Array of urls that should be included next, in order. 24 * @type {Array} 25 * @private 26 */ 27window.queue_ = []; 28 29/** 30 * Custom function for importing ChromeVox scripts. 31 * @param {string} src The JS file to import. 32 * @return {boolean} Whether the script was imported. 33 */ 34window.CLOSURE_IMPORT_SCRIPT = function(src) { 35 // Only run our version of the import script 36 // when trying to inject ChromeVox scripts. 37 if (src.indexOf('chrome-extension://') == 0) { 38 if (!goog.inHtmlDocument_() || 39 goog.dependencies_.written[src]) { 40 return false; 41 } 42 goog.dependencies_.written[src] = true; 43 function loadNextScript() { 44 if (goog.global.queue_.length == 0) 45 return; 46 47 var src = goog.global.queue_[0]; 48 49 if (window.CLOSURE_USE_EXT_MESSAGES) { 50 var relativeSrc = src.substr(src.indexOf('closure/..') + 11); 51 chrome.extension.sendMessage( 52 {'srcFile': relativeSrc}, 53 function(response) { 54 try { 55 eval(response['code']); 56 } catch (e) { 57 console.error('Script error: ' + e + ' in ' + src); 58 } 59 goog.global.queue_ = goog.global.queue_.slice(1); 60 loadNextScript(); 61 }); 62 return; 63 } 64 window.console.log('Using XHR'); 65 66 // Load the script by fetching its source and running 'eval' on it 67 // directly, with a magic comment that makes Chrome treat it like it 68 // loaded normally. Wait until it's fetched before loading the 69 // next script. 70 var xhr = new XMLHttpRequest(); 71 var url = src + '?' + new Date().getTime(); 72 xhr.onreadystatechange = function() { 73 if (xhr.readyState == 4) { 74 var scriptText = xhr.responseText; 75 // Add a magic comment to the bottom of the file so that 76 // Chrome knows the name of the script in the JavaScript debugger. 77 scriptText += '\n//# sourceURL=' + src + '\n'; 78 eval(scriptText); 79 goog.global.queue_ = goog.global.queue_.slice(1); 80 loadNextScript(); 81 } 82 }; 83 xhr.open('GET', url, false); 84 xhr.send(null); 85 } 86 goog.global.queue_.push(src); 87 if (goog.global.queue_.length == 1) { 88 loadNextScript(); 89 } 90 return true; 91 } else { 92 return goog.writeScriptTag_(src); 93 } 94}; 95