JavaScript (index.html):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | <button id= "test" >Click Me</button> <script type= "text/javascript" > var iframeboxy = { current : null , queue : [], request : function (q) { var iframe = document.createElement( "iframe" ); iframe.style.display = "none" ; iframe.name = "iframeboxy" ; iframe.src = q.url; if (iframe.attachEvent) { //IE iframe.attachEvent( "onload" , function () { iframeboxy.callback(iframe); }); } else { iframe.onload = function () { iframeboxy.callback( this ); }; } this .queue.push({ iframe : iframe, data : q.data }); if (! this .current) this .action(); }, action : function () { this .current = null ; if ( this .queue.length) { this .current = this .queue.shift(); document.getElementsByTagName( "body" )[0].appendChild( this .current.iframe); } }, callback : function (e) { this .current.data((e.contentDocument) ? e.contentDocument : e.contentWindow.document); document.getElementsByTagName( "body" )[0].removeChild( this .current.iframe); this .action(); } }; document.getElementById( "test" ).onclick = function () { iframeboxy.request({ url : "robots.txt" , data : function (e) { alert(e.documentElement.getElementsByTagName( "pre" )[0].innerHTML); } }); }; </script> |
範例結果:
說明:
使用純JavaScript動態在Head產生Iframe後,呼叫函式取得Text資料。 支援Chrome、FireFox、IE10,由於Browser本身限制僅能讀取Local檔案。
沒有留言:
張貼留言