我想查找自己的js文件的腳本路徑。如何從他自己的js文件中找到腳本路徑
所以我想要有一個字符串「C:\ files \ MyProject \ MyScripts \ MyJavaScript.js」。
這怎麼可能?
我想查找自己的js文件的腳本路徑。如何從他自己的js文件中找到腳本路徑
所以我想要有一個字符串「C:\ files \ MyProject \ MyScripts \ MyJavaScript.js」。
這怎麼可能?
這裏是我如何做它:
function ScriptPath() {
var scriptPath = '';
try {
//Throw an error to generate a stack trace
throw new Error();
}
catch(e) {
//Split the stack trace into each line
var stackLines = e.stack.split('\n');
var callerIndex = 0;
//Now walk though each line until we find a path reference
for(var i in stackLines){
if(!stackLines[i].match(/http[s]?:\/\//)) continue;
//We skipped all the lines with out an http so we now have a script reference
//This one is the class constructor, the next is the getScriptPath() call
//The one after that is the user code requesting the path info (so offset by 2)
callerIndex = Number(i) + 2;
break;
}
//Now parse the string for each section we want to return
pathParts = stackLines[callerIndex].match(/((http[s]?:\/\/.+\/)([^\/]+\.js)):/);
}
this.fullPath = function() {
return pathParts[1];
};
this.path = function() {
return pathParts[2];
};
this.file = function() {
return pathParts[3];
};
this.fileNoExt = function() {
var parts = this.file().split('.');
parts.length = parts.length != 1 ? parts.length - 1 : 1;
return parts.join('.');
};
}
客戶端無法訪問物理路徑。儘管您可以獲得script
標記的src
屬性。
服務器端你可以得到物理路徑。例如(C#):
Path.GetFullPath(path)
爲了找到URL的完整路徑,在JavaScript中使用location.href
只有在文件系統上運行時纔有效。 – 2014-09-05 07:37:04
如果你可以定義服務器作爲常數變量的絕對路徑,
你可以做到這一點通過鑄造從window.location.href
。從window.location.href
刪除主機前綴window.location.host
,並準備好服務器的絕對路徑。
嘗試:
console.log(window.location.href);
嘗試這種解決方案。我想,這正是ü希望什麼:)
將這個代碼在每個鏈接的腳本文件
var scriptEls = document.getElementsByTagName('script');
var thisScriptEl = scriptEls[scriptEls.length - 1];
var scriptPath = thisScriptEl.src;
var scriptFolder = scriptPath.substr(0, scriptPath.lastIndexOf('/')+1);
console.log(scriptPath +" "+ scriptFolder);// you can save these in any variable also
我這個HTML代碼,測試它的:
<!DOCTYPE html>
<html>
<head>
<title>testing...</title>
<script type="text/javascript" src="test.js"></script>
<script type="text/javascript" src="js/test2.js"></script>
<script type="text/javascript" src="../test3.js"></script>
</head>
<body>
content area
</body>
</html>
,發現這個輸出在控制檯:
file:///D:/workspace/dbshell/www/test.js file:///D:/workspace/dbshell/www/ test.js:6
file:///D:/workspace/dbshell/www/js/test2.js file:///D:/workspace/dbshell/www/js/ test2.js:6
file:///D:/workspace/dbshell/test3.js file:///D:/workspace/dbshell/ test3.js:6
特別感謝meouw .. 合Ë這有助於..
你可以嘗試(jQuery的):
var myScriptDetails = $('script');
myScriptDetails將包含有關腳本的詳細信息,包括它的位置。
myScriptDetails將包含頁面上鍊接的所有腳本的詳細信息。這裏的問題是腳本文件將如何找到它自己的位置。 – xxbinxx 2014-09-06 04:46:19
它的完全不清楚... – 2014-09-05 07:08:40
可能重複[獲取腳本路徑(http://stackoverflow.com/questions/2161159/get-script-path ) – ashokhein 2014-09-05 07:10:34
爲什麼你需要腳本路徑?如果您只想知道js文件的位置以瞭解執行情況,則可以搜索此文件。 – 2014-09-05 07:19:29