Hatena::Groupmoz-addon

Ci.nsIZIGOROu

2008-05-23

Components.utils.import をエミュレート

| 16:26 |  Components.utils.import をエミュレート - Ci.nsIZIGOROu を含むブックマーク はてなブックマーク -  Components.utils.import をエミュレート - Ci.nsIZIGOROu

注意!

本物とだいぶ挙動が違うし、実現不可能だと分かったので参考にしないで下さい。

ソース

こんな感じかねぇ?

(function() {
   var nativeComponents = Components;

   var XPCComponents_Utils_ImportInternal = function() {
	 this.loader = Components.classes["@mozilla.org/moz/jssubscript-loader;1"].getService(Components.interfaces.mozIJSSubScriptLoader);
	 this.ios = Components.classes["@mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService);
   };

   XPCComponents_Utils_ImportInternal.prototype = {
	 cache: {},
	 import: function(uriSpec, jsObj) {
	   var uri = this.ios.newURI(uriSpec, null, null);
	   try {
		 if (uri.scheme != "resource" && uri.scheme != "file") {
		   throw new Error("NS_ERROR_ILLEGAL_VALUE");
		 }

		 var exports = this.cache[uriSpec];

		 if (!exports) {
		   exports = {};
		   this.loader.loadSubScript(uriSpec, exports);
		 }

		 if (exports.EXPORTED_SYMBOLS) {
		   var ex_symbol;
		   for (var i = 0, l = exports.EXPORTED_SYMBOLS.length; i < l; i++) {
			 ex_symbol = exports.EXPORTED_SYMBOLS[i];
			 jsObj[ex_symbol] = exports[ex_symbol];
		   }
		 }
	   }
	   catch (e) {
		 throw e;
	   }
	   return;
	 }
   };

   var internal = new XPCComponents_Utils_ImportInternal();
   var XPCComponents_Utils_Wrapper = function() {};
   XPCComponents_Utils_Wrapper.prototype.import = function(uriSpec, jsObj) { internal.import(uriSpec, jsObj); };

   XPCComponents_Utils_Wrapper.prototype.toString = function() { return "[object nsXPCComponents]"; };

   var prop;
   for (prop in nativeComponents.utils)
	 XPCComponents_Utils_Wrapper.prototype[prop] = nativeComponents.utils[prop];
   var XPCComponents_Wrapper = function() { };

   for (prop in nativeComponents)
	 if (prop != "utils")
	   XPCComponents_Wrapper.prototype[prop] = nativeComponents[prop];

   XPCComponents_Wrapper.prototype.utils = new XPCComponents_Utils_Wrapper();
   XPCComponents_Wrapper.prototype.toString = function() { return "[object nsXPCComponents]"; };

   Components = new XPCComponents_Wrapper();
})();

問題点

  • Componentsごとまるっと変えちゃう所、危ない
  • importの挙動が本当に合ってるかどうか

こういう解法よりも、wrapper作って切り替えのがいいんだろうなぁ。