OLD | NEW |
(Empty) | |
| 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. |
| 4 |
| 5 function Loader(pages) { |
| 6 this.pages_ = pages; |
| 7 this.pages_loaded_ = false; |
| 8 this.loaded_count_ = false; |
| 9 } |
| 10 |
| 11 // Global instance. |
| 12 Loader.instance_ = null; |
| 13 // Alarm name. |
| 14 Loader.ALARM_NAME = 'BkgLoaderAlarm'; |
| 15 // Initial delay. |
| 16 Loader.DELAY_IN_MINUTES = 1; |
| 17 // Periodic wakeup delay. |
| 18 Loader.PERIOD_IN_MINUTES = 60; |
| 19 // Delayed closing of the background page once when all iframes are loaded. |
| 20 Loader.UNLOAD_DELAY_IN_MS = 10000; |
| 21 |
| 22 // static. |
| 23 Loader.getInstance = function() { |
| 24 if (!Loader.instance_) |
| 25 Loader.instance_ = new Loader(g_pages); |
| 26 |
| 27 return Loader.instance_; |
| 28 }; |
| 29 |
| 30 // Alarm event handler. |
| 31 Loader.onAlarm = function(alarm) { |
| 32 Loader.getInstance().onAlarm_(alarm); |
| 33 }; |
| 34 |
| 35 // Loader start up. Kicks off alarm initialization if needed. |
| 36 Loader.prototype.start = function() { |
| 37 console.log('Starting background loader'); |
| 38 chrome.alarms.onAlarm.addListener(Loader.onAlarm); |
| 39 // Check if this alarm already exists, if not then create it. |
| 40 chrome.alarms.get(Loader.ALARM_NAME, function(alarm) { |
| 41 if (!alarm) { |
| 42 console.log('Creating alarm!'); |
| 43 chrome.alarms.create(Loader.ALARM_NAME, |
| 44 {delayInMinutes: Loader.DELAY_IN_MINUTES, |
| 45 periodInMinutes: Loader.PERIOD_IN_MINUTES}); |
| 46 window.close(); |
| 47 return; |
| 48 } |
| 49 console.log('Has alarm already!'); |
| 50 }.bind(this)); |
| 51 }; |
| 52 |
| 53 Loader.prototype.onAlarm_ = function(alarm) { |
| 54 console.log('Got alarm ' + alarm.name); |
| 55 if (this.pages_loaded_) { |
| 56 console.log('Pages already loaded!'); |
| 57 return; |
| 58 } |
| 59 for (i = 0; i < this.pages_.length; i++) { |
| 60 this.loadPage_(i, this.pages_[i]); |
| 61 } |
| 62 this.pages_loaded_ = true; |
| 63 }; |
| 64 |
| 65 Loader.prototype.loadPage_ = function(index, pageUrl) { |
| 66 var iframe = document.createElement('iframe'); |
| 67 iframe.onload = function() { |
| 68 this.loaded_count_++; |
| 69 console.log('Total ' + this.loaded_count_ + ' pages loaded.'); |
| 70 if (this.loaded_count_ < this.pages_.length) |
| 71 return; |
| 72 |
| 73 console.log('All pages loaded!'); |
| 74 // Delay closing. |
| 75 setInterval(function() { |
| 76 console.log('Closing background page.'); |
| 77 window.close(); |
| 78 }.bind(this), Loader.UNLOAD_DELAY_IN_MS); |
| 79 }.bind(this); |
| 80 iframe.src = pageUrl; |
| 81 iframe.name = 'frame' + index; |
| 82 document.body.appendChild(iframe); |
| 83 }; |
| 84 |
| 85 Loader.getInstance().start(); |
OLD | NEW |