0

當動態創建腳本元素並將其添加到頁面時,我的錯誤不會給我腳本的行號,而是我追加腳本的行號。如何獲取動態添加的<script>標記中的錯誤的行號?

下面的代碼在.js文件中時會給出行號document.appendChild(script)所在的行號錯誤。代碼片段,如果運行,將返回正確的行號。他們如何做到這一點?

var script = document.createElement("script"); 
 
script.innerHTML = "\n\n\n\n\n\n\nfoo.bar"; //error should be on line 8 
 

 
document.head.appendChild(script)

+0

http://meta.stackoverflow.com/questions/336082/the-searchbar-works-better-with-tags-than-questions-explaining-this-could-reduc?noredirect=1#comment403450_336082 –

+0

東西出現了在邊欄http://stackoverflow.com/questions/20838067/catch-js-errors-when-adding-a-script-dynamically?rq=1 –

+0

先前的問題啓發了這一答案,但它不真的顯示它。 –

回答

0

明白了。添加代碼周圍的一個嘗試捕捉的偉大工程

catchableScript = function(scriptText) { 
    var scriptText = "try {\n"+scriptText+"\n} \n catch(ex){console.log(ex.lineNumber-1)}"; 

    var script = document.createElement("script"); 
    script.innerHTML = scriptText; 

    document.head.appendChild(script) 

} 

catchableScript("\n\n\n\n\n\n\nfoo.bar"); 

輸出:8

而且,除了有這是有用的信息,但是這是問題的答案。

編輯:

對於那些誰想要它,添加以下代碼:

window.CURRENTLY_EVALED_SCRIPT = scriptText; 
var scriptText = "try {\n"+scriptText 
    +"\n} catch(ex){\n" 
    +"var lineNumber = ex.lineNumber-1;\n" 
    +"var errorOut = {};\n" 
    +"errorOut.exception = ex;\n" 
    +"errorOut.lines = window.CURRENTLY_EVALED_SCRIPT.split('\\n');\n" 
    +"var line = errorOut.lines[lineNumber-1];\n" 
    +"console.log(ex.message+' on line\\n'+line+' :: '+lineNumber, window.CURRENTLY_EVALED_SCRIPT_ELEMENT, errorOut);\n" 
      +"}"; 

    ... 

window.CURRENTLY_EVALED_SCRIPT_ELEMENT = script 

將導致控制檯輸出:

foo is not defined on line 
foo.bar :: 8, <script>, Object { exception: ReferenceError, lines: Array[8] } 

你也可以點擊<script>去添加元素或lines以查看所有行的數組。

工程就像一個魅力。

-1

當你說 「行號」,你可能指的是文件的行號。但在這種情況下,它是哪個文件?您正在動態創建腳本,所以實際上沒有一個。

您創建的腳本僅存在於DOM中,即代碼的內存中表示。這似乎與我預期的完全一樣。

+0

我想是這樣,但是如果你發現錯誤,你可以從eval中得到一塊麻布。我目前正在檢查是否可以使用window ... onerror捕獲它,然後獲取行號 –

+0

nope。 window.onerror調用只是一個錯誤的字符串 –