在Javascript中以任何方式知道从哪个主机脚本加载? [英] In Javascript any way to know what host script was loaded from?

查看:51
本文介绍了在Javascript中以任何方式知道从哪个主机脚本加载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在javascript中,作为从somer主机加载的脚本,有没有办法知道我从哪个服务器/主机加载?我需要向主机发送额外的ajax请求,并且更愿意动态地找出主机。

In javascript, as a script loaded from somer host, is there any way to know what server/host I was loaded from? I need to make additional ajax requests back to that host and would prefer to figure out the host dynamically.

所以如果你在页面上包含一个javascript文件

So if you include a javascript file on a page

<script src="http://somehost.com/js/test.js"></script>

当javascript执行时,在test.js内...

when that javascript execute, within test.js ...

var host_loaded_from = ??? // should be somehost.com 

谢谢

推荐答案


有什么方法可以知道从哪里加载了 I 服务器/主机?

是的,当使用 defer 或<$异步加载脚本时,可能除外c $ c> async 属性,因为在这种情况下,DOM中的最后一个脚本可能不一定是当前正在执行的脚本。有关更多信息,请参阅@kangax的评论。

Yes, it's possible except when the script is loaded asynchronously using defer or async attributes since the last script in the DOM may not necessarily be the currently executing script in that case. See the comments by @kangax for more information.

此外,同样的问题最近发布。

在test.js中,获取最后一个脚本元素目前正在解析脚本(在你的情况下是test.js),并得到它的 src

Inside your test.js, get the last script element which will be the currently being parsed script (test.js in your case), and get its src.

// test.js
var scripts = document.getElementsByTagName('script');
var src = scripts[scripts.length - 1].src;

找到一个 src ,解析主机使用正则表达式。

One the src is found, parsed the host using regex.

src.match(new RegExp('https?://[^/]*'))
["http://somehost.com"] // for your example

这篇关于在Javascript中以任何方式知道从哪个主机脚本加载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆