2013-03-28 52 views
1

我正在使用NODE JS模塊創建HTTP服務器。服務器的響應是一個包含JavaScript的頁面,其中嵌入了一個網頁,並在此我正在使用getElementsByTagName訪問其元素數據。
這是響應代碼:getElementsByTagName不起作用

<html> 
<head> 
<script type='text/javascript'> 
    function test() { 
     document.body.innerHTML='<iframe id="ifool" src="file:///C:/Users/Naman/Desktop/rew.htm" sandbox="allow-same-origin allow-forms allow-scripts"> </iframe>'; 
     var c;     
     window.setInterval(function(){ 
     c=document.getElementById("ifool").contentWindow.location.href; 
     window.history.pushstate(0,0,c); 
     },100); 
     window.setInterval(function() { 
     var x = document.getElementById("ifool"); 
     var y = (x.contentWindow || x.contentDocument); 
     if (y.document) y = y.document; 
     try { 
      var a = y.getElementsByTagName("input")[0].value; 
      var b = y.getElementsByTagName("input")[1].value; 
     } catch (err) { 
      txt = "There was an error on this page.\n\n"; 
      txt += "Error description: " + err.message + "\n\n"; 
      txt += "Click OK to continue.\n\n"; 
      alert(txt); 
     } 
     }, 2000); 
</script> 
</head> 
<body onload= 'test()'> 
</body> 
</html> 

我在這裏得到錯誤的「對象[對象全局]沒辦法‘的getElementsByTagName’」。我正在使用Chrome,但我也嘗試過Firefox。
在檢查元素控制檯我也越來越以下錯誤 -

Uncaught TypeError: Object #<History> has no method 'pushstate' localhost: Unsafe JavaScript attempt to access frame with URL file:///C:/Users/Naman/Desktop/rew.htm from frame with URL http://localhost:8080/. Domains, protocols and ports must match. 
+1

你能爲我們'console.log(x)'和'console.log(y)'並且將結果添加到你的問題嗎? –

+0

我認爲你正在嘗試做'var a = x.getElementsByTagName(「input」)[0] .value;'而不是在那裏提到'y'。 –

+0

在我的opnion中,y = null或undefined ...你用什麼瀏覽器? – Pouki

回答

1

第一個錯誤是由這一行造成的:

window.history.pushstate(0,0,c); 

正確的代碼是:

window.history.pushState(0,0,c); 

注意大寫S

至於另一個錯誤,在本地查看文件時,無法訪問iframe和其他「受限制」功能,例如AJAX。您必須將其上傳到服務器(或在本地計算機上啓動服務器)才能使用這些功能。

+0

如果我使用一些URL而不是本地文件仍然給我同樣的錯誤。 – Naman

+0

這是因爲「某個URL」與您的文件來源不同。 –