有没有办法在外部javascript文件中,可以知道文件的主机?
例如,如果我有网站 http://hostOne.com/index.php
,文件 index.php
的代码:
<html>
<head>
<script type="text/javascript" src="http://hostTwo.com/script/test.js"></script>
</head>
<body>
<div>...</div>
</body>
</html>
我需要在文件 test.js
中可以知道主机 http://hostTwo.com
。
谢谢。
编辑
或者它可以知道被调用的标签“script”?使用这个选项我可以分析标签并获得“src”属性。但我不想依赖文件 test.js
的名称来分析包含该站点的所有标记 script
。
*解决方案基于@Armi *
HTML:
<html>
<head>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script id="idscript" type="text/javascript" src="http://hostTwo.com/script/test.js"></script>
</head>
<body>
<div>...</div>
</body>
</html>
JS 代码
var
url = $('head').find('#idscript').attr('src'),
host = url.replace(/(\/\/.*?\/).*/g, '$1');
console.log(host);
最佳答案
我有一个想法(基于 jQuery 的代码片段):
var yourScriptTag = $('head').find('script[src$="jquery-1.7.1.js"]').eq(0);
var theHostnameOfYourScript = $(yourScriptTag).attr('src').replace(/(http:\/\/.*?\/).*/g, '$1');
alert(theHostnameOfYourScript);
jsfiddle 示例:http://alpha.jsfiddle.net/XsJn8/
如果您知道脚本的文件名(如果它始终相同且唯一),您可以使用此代码段来获取主机名。
如果此路径是相对路径(并且不包含主机),您可以使用简单的 location.hostname
关于javascript - 如何使外部 javascript 文件知道自己的主机?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9211339/