獲取js腳本的絕對路徑


腳本運行在Web中

使用以下代碼即可獲取:

globalThis.document.currentScript.src

document.currentScript返回的是當前執行的script元素;然后調用script元素的src屬性即可獲取腳本文件的絕對路徑。

腳本運行在WebWorker中

WebWorker不可以訪問document對象. 但是可以通過以下方式獲取絕對路徑:

globalThis.location.href

腳本運行在Node.js中

__filename // 控制台中未定義
module.filename // 推薦

通用函數

/**
 * 獲取運行該函數的腳本的絕對路徑
 */
function get_absolute_path() {
    if (globalThis.constructor.name === 'Window') return (document.currentScript && document.currentScript.src) || document.location.href;
    if (globalThis.constructor.name === 'DedicatedWorkerGlobalScope') return globalThis.location.href;
    if (globalThis.constructor.name === 'Object') return module.filename;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM