OSDN Git Service

Version 0.6.205, bug fixes X.Net.Form, update X.HTMLAudio for iOS7+.
[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  * https://web.archive.org/web/20120917100043/http://d.hatena.ne.jp/yuushimizu/20090128/1233146321
9  * TODO JSONPの動的取得+エラー処理
10  * http://d.hatena.ne.jp/NeoCat/20110206/1296934235
11  * 
12  * Safari が JavaScript ファイルを動的ロードできない件
13  * http://www.bricklife.com/weblog/000618.html
14  * 
15  * IE9でiframe内で遷移した場合window.parentのメソッドを呼べない 
16  * http://kozo002.blogspot.jp/2012/07/ie9iframewindowparent.html
17  * 
18  * IE6(IETester,localhost) で動かない,
19  * 
20  * TODO iframe 内を他ドメインにして jsonp のセキュリティを強化。他ドメインに jsonp を読み込んで 正しい JSON か?検証後にフレーム間通信で戻す。
21  */
22
23         // TODO chashe
24         // TODO iframe useful or not. TODO check dynamicIframe
25         // TODO file: では http: は使えない
26
27 X_TEMP.X_JSONP_cb = function( accessKey, jsonString, time, opt_json2FileSize ){
28                         if( accessKey !== X_JSONP_ACCESS_KEY || !X_JSONP._busy ) return;
29                         
30                         X_JSONP._busy = false;
31                         
32                         X_JSONP
33                                 [ 'asyncDispatch' ]( {
34                                         type     : jsonString ? X_EVENT_SUCCESS : X_EVENT_ERROR,
35                                         response : X_JSON_parseTrustableString( jsonString )
36                                 } );
37                         
38                         X_JSONP_errorTimerID && X_Timer_remove( X_JSONP_errorTimerID );
39                         
40                         console.log( 'ms : ' + time + ' speed : ' + ( ( jsonString.length + ( opt_json2FileSize || 0 ) ) / time * 1000 ) + ' バイト/秒.' );
41         };
42
43 var X_JSONP_ACCESS_KEY = Math.random(),
44         
45         X_JSONP_maxOnloadCount,
46         
47         X_JSONP_onloadCount = 0,
48         
49         X_JSONP_errorTimerID;
50
51 X_TEMP.X_JSONP_init = function(){
52         X[ 'Net' ][ '__json_cb__' ] = X_TEMP.X_JSONP_cb;
53         
54         X_JSONP = X_Class_override( X_NinjaIframe(), X_TEMP.X_JSONP_params );
55         
56         delete X_TEMP.X_JSONP_cb;
57         delete X_TEMP.X_JSONP_init;
58         delete X_TEMP.X_JSONP_params;
59         
60         return X_JSONP;
61 };
62
63 X_TEMP.X_JSONP_params = {
64         
65                         _busy         : false,
66                         _canceled     : false,
67                         
68                         load : function( option ){
69                                 //createURL
70                                 var url           = option[ 'url' ],
71                                         callback      = option[ 'callbackName' ],
72                                         charset       = option[ 'charset' ],
73                                         json2Path     = window.RegExp ? 'js/libs/json2.js' : 'js/libs/json2_regfree.js',
74                                         json2FileSize = 18103,
75                                         html;
76                                 
77                                 // file プロトコルで外部アクセスの禁止
78                                 if( !X_URL_isSameProtocol( url ) ){
79                                         return X_JSONP[ 'asyncDispatch' ]( X_EVENT_ERROR );
80                                 };
81
82                                 if( !callback && !( callback = X_URL_paramToObj( url.split( '?' )[ 1 ] )[ 'callback' ] ) ){
83                                         url += '&callback=cb';
84                                         callback = 'cb';
85                                 };
86                                 
87                                 charset = charset ? ' charset="' + charset + '"' : '';
88                                 
89                                 // TODO '<scr'+'ipt> 化 恐らくアンチウイルスソフトが反応しないための対策
90                                 // document.postMessage()→window.postMessage() (Opera 9.50 build 9841 -)
91                                 // http://d.hatena.ne.jp/cnrd/20080518/1211099169
92                                 // 最近の仕様変更(引数のtargetOriginとかMessageEventのoriginとか)にはまだ対応してないみたい 
93                         
94                                 if( X_UA[ 'Opera' ] ){
95                                         html = [
96                                                 ( window[ 'JSON' ] ? '' : '<script src="' + json2Path + '"></script>' ),
97                                                 '<script>',
98                                                         'onunload=function(){im.onload=im.onerror=""};',
99                                                         'nw=+new Date;',
100                                                         'function ', callback, '(o){if(nw){nw-=+new Date;parent.X.Net.__json_cb__(' + X_JSONP_ACCESS_KEY + ',JSON.stringify(o),-nw', window[ 'JSON' ] ? json2FileSize : 0 ,');nw=0}}',
101                                                 '</script>',    
102                                                 '<script', charset, ' id="jp"></script>',
103                                                 '<img id="im" src="', url, '" onload="jp.src=im.src" onerror="jp.src=im.src">'
104                                         ];
105                                         X_JSONP_maxOnloadCount = 2;
106                                 } else
107                                 if( X_UA[ 'IE8' ] ){
108                                         html = [
109                                                 '<script', charset, ' id="jp"></script>',
110                                                 '<script>',
111                                                         'onunload=function(){clearTimeout(id)};',
112                                                         'nw=0;', // なぜか必要,,,
113                                                         'function ', callback, '(o){nw-=+new Date;parent.X.Net.__json_cb__(' + X_JSONP_ACCESS_KEY + ',parent.X.JSON.stringify(o),-nw)}',
114                                                         //'function ', callback, '(o){if(nw){nw-=+new Date;postMessage("', X_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}}',                   
115                                                         'function tm(){jp.src="', url ,'";nw=+new Date}',
116                                                         'id=setTimeout(tm,16);',
117                                                 '</script>'
118                                                 
119                                                 /* 以下のコードは XP ie8 では動くけど、win8 IE11(8モード)で動かない 開発の便宜を取って,setTimeout を挟む
120                                                 '<script>',
121                                                         'function ', callback, '(o){window.parent.X.Net.__json_cb__(' + X_JSONP_ACCESS_KEY + ',window.parent.JSON.stringify(o))}',
122                                                 '</script>',
123                                                 '<script src="', url, '"></script>' */
124                                         ];
125                                         X_JSONP_maxOnloadCount = 2;
126                                 } else
127                                 if( X_UA[ 'IE9' ] ){
128                                         html = [
129                                                 '<script', charset, ' id="jp"></script>',
130                                                 '<script>',
131                                                         'onunload=function(){clearTimeout(id)};',
132                                                         'function ', callback, '(o){nw-=+new Date;parent.X.Net.__json_cb__(' + X_JSONP_ACCESS_KEY + ',JSON.stringify(o),-nw)}',
133                                                         'function tm(){jp.src="', url ,'";nw=+new Date}',
134                                                         'id=setTimeout(tm,16);',
135                                                 '</script>'
136                                         ];
137                                         X_JSONP_maxOnloadCount = 2;
138                                 } else
139                                 if( window[ 'JSON' ] ){
140                                         html = [        
141                                                 '<script>',
142                                                         'nw=+new Date;',
143                                                         'function ', callback, '(o){if(nw){nw-=+new Date;parent.X.Net.__json_cb__(' + X_JSONP_ACCESS_KEY + ',JSON.stringify(o),-nw);nw=0}}',
144                                                         //'function ', callback, '(o){if(nw){nw-=+new Date;parent.postMessage("', X_JSONP_SEND_MSG_KEY,' "+nw+"|"+JSON.stringify(o),"', location.origin, '");nw=0}}',
145                                                 '</script>',
146                                                 '<script', charset, ' src="', url, '"></script>'
147                                         ];
148                                         X_JSONP_maxOnloadCount = 1;
149                                 } else
150                                 if( X_UA[ 'IE4' ] || X_UA[ 'MacIE' ] ){
151                                         html = [
152                                                 '<script id="jn"></script>',
153                                                 '<script', charset, ' id="jp"></script>',
154                                                 '<script>',
155                                                         'onunload=function(){clearTimeout(id)};',
156                                                         'function ', callback, '(o){nw-=new Date;parent.X.Net.__json_cb__(' + X_JSONP_ACCESS_KEY + ',JSON.stringify(o),-nw-16,', json2FileSize, ')}',
157                                                         'function t1(){document.all.jn.src="', json2Path ,'";id=setTimeout("t2()",16);nw=+new Date}',
158                                                         'id=setTimeout("t1()",16);',
159                                                         'function t2(){if(window.JSON){document.all.jp.src="', url ,'"}else{id=setTimeout("t2()",16)}}',
160                                                 '</script>'
161                                         ];
162                                         X_JSONP_maxOnloadCount = 3;
163                                 } else
164                                 if( X_UA[ 'IE' ] < 8 ){ // ie5-7
165                                         html = [
166                                                 '<script id="jn"></script>',
167                                                 '<script', charset, ' id="jp"></script>',
168                                                 '<script>',
169                                                         'onunload=function(){clearTimeout(id)};',
170                                                         'function ', callback, '(o){nw-=new Date;parent.X.Net.__json_cb__(' + X_JSONP_ACCESS_KEY + ',JSON.stringify(o),-nw-16,', json2FileSize, ')}',
171                                                         'function t1(){jn.src="', json2Path ,'";id=setTimeout(t2,16);nw=+new Date}',
172                                                         'id=setTimeout(t1,16);',
173                                                         'function t2(){if(window.JSON){jp.src="', url ,'"}else{id=setTimeout(t2,16)}}',
174                                                 '</script>'
175                                         ];
176                                         X_JSONP_maxOnloadCount = 3;
177                                 } else {
178                                         html = [
179                                                 '<script>',
180                                                         'function ', callback, '(o){if(nw){nw-=new Date;parent.X.Net.__json_cb__(' + X_JSONP_ACCESS_KEY + ',JSON.stringify(o),-nw,', json2FileSize, ');nw=0}}',
181                                                         'nw=+new Date;',
182                                                 '</script>',
183                                                 '<script src="', json2Path, '"></script>',
184                                                 '<script', charset, ' src="', url, '"></script>'
185                                         ];
186                                         X_JSONP_maxOnloadCount = 2;
187                                 };
188                                 
189                                 X_JSONP
190                                         [ 'refresh' ]( html.join( '' ) )
191                                         [ 'listen' ]( [ 'ninjaload', 'ninjaerror' ], X_JSONP_iframeListener );
192                                                         
193                                 X_JSONP._busy = true;
194                         },
195                         
196                         cancel : function(){
197                                 X_JSONP.reset();
198                                 X_JSONP._canceled = true;
199                         },
200                         
201                         reset : function(){
202                                 X_JSONP._busy = X_JSONP._canceled = false;
203                                 X_JSONP[ 'unlisten' ]( [ 'ninjaload', 'ninjaerror' ], X_JSONP_iframeListener );
204                                 X_JSONP[ 'refresh' ]( '' );
205                                 X_JSONP_errorTimerID && X_Timer_remove( X_JSONP_errorTimerID );
206                                 X_JSONP_errorTimerID = X_JSONP_onloadCount = 0;
207                         }
208                 };
209
210 function X_JSONP_iframeListener( e ){
211         switch( e.type ){
212                 case 'ninjaload' :
213                         console.log( 'iframe onload, but ' + X_JSONP_onloadCount + ' < ' + X_JSONP_maxOnloadCount );
214                         if( ++X_JSONP_onloadCount < X_JSONP_maxOnloadCount ) return;
215                         
216                         // TODO callback が無ければ error -> timeout を観る?
217                         X_JSONP_errorTimerID = X_JSONP[ 'asyncDispatch' ]( 1000, X_EVENT_ERROR );
218                         break;
219                 case 'ninjaerror' :
220                         console.log( 'iframe onerror' );
221                         X_JSONP[ 'asyncDispatch' ]( X_EVENT_ERROR );
222                         break;
223         };
224         return X_CALLBACK_UN_LISTEN;
225 };