Index: chrome/common.js |
=================================================================== |
new file mode 100644 |
--- /dev/null |
+++ b/chrome/common.js |
@@ -0,0 +1,62 @@ |
+(function() { |
+ /* Events */ |
+ |
+ WrappedEventTarget = function(target) { |
+ this._listeners = []; |
+ this._wrappedListeners = []; |
+ this._target = target; |
+ }; |
+ WrappedEventTarget.prototype = { |
+ _prepareExtraArguments: function() { |
+ return []; |
+ }, |
+ addListener: function(listener) { |
+ var extaArgs = Array.prototype.slice.call(arguments, 1); |
+ extaArgs = this._prepareExtraArguments.apply(this, extaArgs); |
+ |
+ var wrappedListener = this._wrapListener(listener); |
+ this._listeners.push(listener); |
+ this._wrappedListeners.push(wrappedListener); |
+ |
+ this._target.addListener.apply(this._target, [wrappedListener].concat(extaArgs)); |
+ }, |
+ removeListener: function(listener) { |
+ var idx = this._listeners.indexOf(listener); |
+ |
+ if (idx != -1) { |
+ this._target.removeListener(this._wrappedListeners[idx]); |
+ |
+ this._listeners.splice(idx, 1); |
+ this._wrappedListeners.splice(idx, 1); |
+ } |
+ } |
+ }; |
+ |
+ var MessageEventTarget = function() { |
+ WrappedEventTarget.call(this, chrome.runtime.onMessage); |
+ }; |
+ MessageEventTarget.prototype = { |
+ __proto__: WrappedEventTarget.prototype, |
+ _wrapListener: function(listener) { |
+ return function(message, sender, sendResponse) { |
+ listener(message, {tab: sender.tab && new Tab(sender.tab)}, sendResponse); |
+ }; |
+ } |
+ }; |
+ |
+ /* API */ |
+ |
+ ext = { |
+ backgroundPage: { |
+ sendMessage: function(message, responseCallback) { |
+ chrome.runtime.sendMessage(message, responseCallback); |
+ }, |
+ getDOMWindow: function() { |
+ return chrome.extension.getBackgroundPage(); |
+ } |
+ }, |
+ getURL: chrome.extension.getURL, |
+ onMessage: new MessageEventTarget(), |
+ i18n: chrome.i18n |
+ }; |
+})(); |