简体   繁体   English

Javascript文件中的代码可以知道自己的域/ URL

[英]Can code in a Javascript file know its own domain/URL

If I have a site, example.com, and a page on that site references a Javascript at subdomain.example.com/serveAd.js -- is there a way from within serveAd.js to know its own URL, or the domain from which it was downloaded? 如果我有一个站点,example.com和该站点上的页面引用了subdomain.example.com/serveAd.js上的Javascript - 是否有一种方法可以在serveAd.js中知道自己的URL,或者来自哪个下载了?

(The JS can certainly know all about the page that called it. I want to know if the JS knows about its own origin.) (JS当然可以知道调用它的页面。我想知道JS是否了解它自己的来源。)

If you were using jquery, you could get the full url with this kind of thing: 如果您使用的是jquery,那么您可以通过以下方式获取完整的URL:

var fullJsUrl= $('script[src$=serveAd.js]').attr('src');

If not using jquery, it may take more work, but you get the idea ;) 如果不使用jquery,可能需要更多的工作,但你明白了;)

I'm pretty sure, as the script is parsed that the last <script> node available in the DOM will be the one being parsed. 我很确定,因为解析了<script> ,DOM中可用的最后一个<script>节点将是正在解析的节点。

Try this in an external JS to see: 在外部JS中试试看:

var scripts = document.getElementsByTagName('script');
var lastScript = scripts[scripts.length - 1];
alert(lastScript.src);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM