OSDN Git Service

2c259c5476bcb87c4fafd3a7797513a3f7b03a9d
[pettanr/clientJs.git] / 0.6.x / js / 06_net / 02_XNetJSONP.js
1 //{+jsonp"jsonpによるajax"(jsonpによるクロスドメイン通信。)[+net,+ninjaiframe]
2
3 /*
4  * Operaでも非同期リクエストが並列処理できる img-JSONP
5  * http://developer.cybozu.co.jp/takesako/2007/06/opera_img-jsonp.html
6  * 
7  * iframe を使った jsonp の読み込みエラー判定の記事、
8  * JSONPのエラーを判断する は web archive でも観れない
9  * http://d.hatena.ne.jp/yuushimizu/20090128/1233146321
10  * TODO JSONPの動的取得+エラー処理
11  * http://d.hatena.ne.jp/NeoCat/20110206/1296934235
12  * 
13  * Safari が JavaScript ファイルを動的ロードできない件
14  * http://www.bricklife.com/weblog/000618.html
15  * 
16  * IE9でiframe内で遷移した場合window.parentのメソッドを呼べない 
17  * http://kozo002.blogspot.jp/2012/07/ie9iframewindowparent.html
18  * 
19  * IE6(IETester,localhost) で動かない,
20  * 
21  * TODO iframe 内を他ドメインにして jsonp のセキュリティを強化。他ドメインに jsonp を読み込んで 正しい JSON か?検証後にフレーム間通信で戻す。
22  */
23
24         // TODO chashe
25         // TODO iframe useful or not. TODO check dynamicIframe
26         // TODO file: では http: は使えない
27
28 X[ 'Net' ][ 'JSONP' ] = {
29         'cb' : function( accessKey, jsonString, time, opt_json2FileSize ){
30                         if( accessKey !== X_NET_JSONP_ACCESS_KEY || !X_NET_JSONPWrapper._busy ) return;
31                         
32                         X_NET_JSONPWrapper._busy = false;
33                         
34                         X_NET_JSONPWrapper
35                                 [ 'asyncDispatch' ]( {
36                                         type : jsonString ? X_EVENT_SUCCESS : X_EVENT_ERROR,
37                                         data : X_String_parseTrustedJsonString( jsonString )
38                                 } );
39                         
40                         X_Net_JSONP_errorTimerID && X_Timer_remove( X_Net_JSONP_errorTimerID );
41                         
42                         console.log( 'ms : ' + time + ' speed : ' + ( ( jsonString.length + ( opt_json2FileSize || 0 ) ) / time * 1000 ) + ' バイト/秒.' );
43                 }
44 };
45
46 var X_NET_JSONP_ACCESS_KEY = Math.random(),
47         
48         X_Net_JSONP_maxOnloadCount,
49         
50         X_Net_JSONP_onloadCount = 0,
51         
52         X_Net_JSONP_errorTimerID;
53
54 X_TEMP.X_NET_JSONP_init = function(){
55         X_NET_JSONPWrapper = X_Class_override( X[ 'Util' ][ 'NinjaIframe' ](), X_TEMP.X_NET_JSONP_params );
56         
57         delete X_TEMP.X_NET_JSONP_init;
58         delete X_TEMP.X_NET_JSONP_params;
59         
60         return X_NET_JSONPWrapper;
61 };
62
63 X_TEMP.X_NET_JSONP_params = {
64         
65                         _busy         : false,
66                         _canceled     : false,
67                         
68                         load : function( option ){
69                                 //createURL
70                                 var url           = option[ 'url' ],
71                                         params        = option[ 'params' ],
72                                         callback      = option[ 'callbackName' ],
73                                         charset       = option[ 'charset' ],
74                                         json2Path     = window.RegExp ? 'js/libs/json2.js' : 'js/libs/json2_regfree.js',
75                                         json2FileSize = 18103,
76                                         html;
77                                 
78                                 url = X_URL_create( url, params );
79                                 
80                                 if( !callback && !( callback = X_URL_ParamToObj( url.split( '?' )[ 1 ] )[ 'callback' ] ) ){
81                                         url += '&callback=cb';
82                                         callback = 'cb';
83                                 };
84                                 
85                                 charset = charset ? ' charset="' + charset + '"' : '';
86                                 
87                                 // TODO '<scr'+'ipt> 化 恐らくアンチウイルスソフトが反応しないための対策
88                                 // document.postMessage()→window.postMessage() (Opera 9.50 build 9841 -)
89                                 // http://d.hatena.ne.jp/cnrd/20080518/1211099169
90                                 // 最近の仕様変更(引数のtargetOriginとかMessageEventのoriginとか)にはまだ対応してないみたい 
91                         
92                                 if( X_UA[ 'Opera' ] ){
93                                         html = [
94                                                 ( window[ 'JSON' ] ? '' : '<script src="' + json2Path + '"></script>' ),
95                                                 '<script>',
96                                                         'onunload=function(){im.onload=im.onerror=""};',
97                                                         'nw=+new Date;',
98                                                         'function ', callback, '(o){if(nw){nw-=+new Date;parent.X.Net.JSONP.cb(' + X_NET_JSONP_ACCESS_KEY + ',JSON.stringify(o),-nw', window[ 'JSON' ] ? json2FileSize : 0 ,');nw=0}}',
99                                                 '</script>',    
100                                                 '<script', charset, ' id="jp"></script>',
101                                                 '<img id="im" src="', url, '" onload="jp.src=im.src" onerror="jp.src=im.src">'
102                                         ];
103                                         X_Net_JSONP_maxOnloadCount = 2;
104                                 } else
105                                 if( X_UA[ 'IE8' ] ){
106                                         html = [
107                                                 // JavaScriptでunicode文字列をunescapeする
108                                                 // http://perutago.seesaa.net/article/202801583.html
109                                                 
110                                                 // http://blog.livedoor.jp/dankogai/archives/51503830.html              
111                                                 // Ajax - IE8にもJSON入ってます。使えるとは限らないけど
112                                                 // Compatibility mode (別名Quirks mode) では、JSONオブジェクトは無効になります。iframeもだめです
113                                                 '<script', charset, ' id="jp"></script>',
114                                                 '<script>',
115                                                         'onunload=function(){clearTimeout(id)};',
116                                                         'nw=0;', // なぜか必要,,,
117                                                         'function ', callback, '(o){nw-=+new Date;parent.X.Net.JSONP.cb(' + X_NET_JSONP_ACCESS_KEY + ',parent.JSON.stringify(o).replace(/\\\\u([a-fA-F0-9]{4})/g,function(a,b){return String.fromCharCode(parseInt(b,16))}),-nw)}',
118                                                         //'function ', callback, '(o){if(nw){nw-=+new Date;postMessage("', X_NET_JSONP_SEND_MSG_KEY,' "+nw+"|"+parent.JSON.stringify(o).replace(/\\\\u([a-fA-F0-9]{4})/g,function(a,b){return String.fromCharCode(parseInt(b,16))}),"*");nw=0}}',                       
119                                                         'function tm(){jp.src="', url ,'";nw=+new Date}',
120                                                         'id=setTimeout(tm,16);',
121                                                 '</script>'
122                                                 
123                                                 /* 以下のコードは XP ie8 では動くけど、win8 IE11(8モード)で動かない 開発の便宜を取って,setTimeout を挟む
124                                                 '<script>',
125                                                         'function ', callback, '(o){window.parent.X.Net.JSONP.cb(' + X_NET_JSONP_ACCESS_KEY + ',window.parent.JSON.stringify(o))}',
126                                                 '</script>',
127                                                 '<script src="', url, '"></script>' */
128                                         ];
129                                         X_Net_JSONP_maxOnloadCount = 2;
130                                 } else
131                                 if( X_UA[ 'IE9' ] ){
132                                         html = [
133                                                 '<script', charset, ' id="jp"></script>',
134                                                 '<script>',
135                                                         'onunload=function(){clearTimeout(id)};',
136                                                         'function ', callback, '(o){nw-=+new Date;parent.X.Net.JSONP.cb(' + X_NET_JSONP_ACCESS_KEY + ',JSON.stringify(o),-nw)}',
137                                                         'function tm(){jp.src="', url ,'";nw=+new Date}',
138                                                         'id=setTimeout(tm,16);',
139                                                 '</script>'
140                                         ];
141                                         X_Net_JSONP_maxOnloadCount = 2;
142                                 } else
143                                 if( window[ 'JSON' ] ){
144                                         html = [        
145                                                 '<script>',
146                                                         'nw=+new Date;',
147                                                         'function ', callback, '(o){if(nw){nw-=+new Date;parent.X.Net.JSONP.cb(' + X_NET_JSONP_ACCESS_KEY + ',JSON.stringify(o),-nw);nw=0}}',
148                                                         //'function ', callback, '(o){if(nw){nw-=+new Date;parent.postMessage("', X_NET_JSONP_SEND_MSG_KEY,' "+nw+"|"+JSON.stringify(o),"', location.origin, '");nw=0}}',
149                                                 '</script>',
150                                                 '<script', charset, ' src="', url, '"></script>'
151                                         ];
152                                         X_Net_JSONP_maxOnloadCount = 1;
153                                 } else
154                                 if( X_UA[ 'IE4' ] || X_UA[ 'MacIE' ] ){
155                                         html = [
156                                                 '<script id="jn"></script>',
157                                                 '<script', charset, ' id="jp"></script>',
158                                                 '<script>',
159                                                         'onunload=function(){clearTimeout(id)};',
160                                                         'function ', callback, '(o){nw-=new Date;parent.X.Net.JSONP.cb(' + X_NET_JSONP_ACCESS_KEY + ',JSON.stringify(o),-nw-16,', json2FileSize, ')}',
161                                                         'function t1(){document.all.jn.src="', json2Path ,'";id=setTimeout("t2()",16);nw=+new Date}',
162                                                         'id=setTimeout("t1()",16);',
163                                                         'function t2(){if(window.JSON){document.all.jp.src="', url ,'"}else{id=setTimeout("t2()",16)}}',
164                                                 '</script>'
165                                         ];
166                                         X_Net_JSONP_maxOnloadCount = 3;
167                                 } else
168                                 if( X_UA[ 'IE' ] < 8 ){ // ie5-7
169                                         html = [
170                                                 '<script id="jn"></script>',
171                                                 '<script', charset, ' id="jp"></script>',
172                                                 '<script>',
173                                                         'onunload=function(){clearTimeout(id)};',
174                                                         'function ', callback, '(o){nw-=new Date;parent.X.Net.JSONP.cb(' + X_NET_JSONP_ACCESS_KEY + ',JSON.stringify(o),-nw-16,', json2FileSize, ')}',
175                                                         'function t1(){jn.src="', json2Path ,'";id=setTimeout(t2,16);nw=+new Date}',
176                                                         'id=setTimeout(t1,16);',
177                                                         'function t2(){if(window.JSON){jp.src="', url ,'"}else{id=setTimeout(t2,16)}}',
178                                                 '</script>'
179                                         ];
180                                         X_Net_JSONP_maxOnloadCount = 3;
181                                 } else {
182                                         html = [
183                                                 '<script>',
184                                                         'function ', callback, '(o){if(nw){nw-=new Date;parent.X.Net.JSONP.cb(' + X_NET_JSONP_ACCESS_KEY + ',JSON.stringify(o),-nw,', json2FileSize, ');nw=0}}',
185                                                         'nw=+new Date;',
186                                                 '</script>',
187                                                 '<script src="', json2Path, '"></script>',
188                                                 '<script', charset, ' src="', url, '"></script>'
189                                         ];
190                                         X_Net_JSONP_maxOnloadCount = 2;
191                                 };
192                                 
193                                 X_NET_JSONPWrapper
194                                         [ 'refresh' ]( html.join( '' ) )
195                                         [ 'listen' ]( [ 'ninjaload', 'ninjaerror' ], X_NET_JSONP_iframeListener );
196                                                         
197                                 X_NET_JSONPWrapper._busy = true;
198                         },
199                         
200                         cancel : function(){
201                                 X_NET_JSONPWrapper.reset();
202                                 X_NET_JSONPWrapper._canceled = true;
203                         },
204                         
205                         reset : function(){
206                                 X_NET_JSONPWrapper._busy = X_NET_JSONPWrapper._canceled = false;
207                                 X_NET_JSONPWrapper[ 'unlisten' ]( [ 'ninjaload', 'ninjaerror' ], X_NET_JSONP_iframeListener );
208                                 X_NET_JSONPWrapper[ 'refresh' ]( '' );
209                                 X_Net_JSONP_errorTimerID && X_Timer_remove( X_Net_JSONP_errorTimerID );
210                                 X_Net_JSONP_errorTimerID = X_Net_JSONP_onloadCount = 0;
211                         }
212                 };
213
214 function X_NET_JSONP_iframeListener( e ){
215         switch( e.type ){
216                 case 'ninjaload' :
217                         console.log( 'iframe onload, but ' + X_Net_JSONP_onloadCount + ' < ' + X_Net_JSONP_maxOnloadCount );
218                         if( ++X_Net_JSONP_onloadCount < X_Net_JSONP_maxOnloadCount ) return;
219                         
220                         // TODO callback が無ければ error -> timeout を観る?
221                         X_Net_JSONP_errorTimerID = X_NET_JSONPWrapper[ 'asyncDispatch' ]( 1000, X_EVENT_ERROR );
222                         break;
223                 case 'ninjaerror' :
224                         console.log( 'iframe onerror' );
225                         X_NET_JSONPWrapper[ 'asyncDispatch' ]( X_EVENT_ERROR );
226                         break;
227         };
228         return X_Callback_UN_LISTEN;
229 };