是否可以在运行时确定这一点?
external.js 的内容:
function x() {
//can i get the path/name of the html file that included this js file?
//which is test.html
}
Run Code Online (Sandbox Code Playgroud)
test.html 的内容
脚本 src="external.js"
“包含这个 js 文件的HTML 文件”很简单,它只是当前文档的地址。location.href.
如果您想获取 URL 的特定部分,例如。路径名的最后一部分:
var filename= location.pathname.split('/').pop();
Run Code Online (Sandbox Code Playgroud)
调用函数的 HTML 页面是一个稍微不同的命题,因为在跨文档脚本的世界中,您可以将函数从一个窗口传递到另一个窗口,因此可以从定义函数的不同位置调用该函数。
没有简单或可靠的方法来检测您从何处被调用,但这种情况通常并不常见。一般来说,最好避免跨文档函数调用,因为有许多令人讨厌的陷阱。window.postMessage将来应该会减少这种需求。
| 归档时间: |
|
| 查看次数: |
1198 次 |
| 最近记录: |