简体   繁体   English

从请求脚本的地方获取主机

[英]Get host from where script has been requested

I have a script that other people request on their websites from my host. 我有一个脚本,其他人可以从我的房东在他们的网站上请求。 I have multiple environments (dev/test/production), and within my script, I want to know the environment from which it has been loaded. 我有多个环境(开发/测试/生产),并且在我的脚本中,我想知道从其加载的环境。

For example, I'm serving script.js at the following sites (the file is the same on all sites): 例如,我在以下站点提供script.js (文件在所有站点上都相同):

dev.mysite.com/script.js
test.mysite.com/script.js
www.mysite.com/script.js

Someone loads my script as: 有人将我的脚本加载为:

<script src="dev.mysite.com/script.js"></script>

So within script.js , I want to have some code which is able to get the host from which the script itself has been requested from: 因此,在script.js ,我想要一些代码,该代码能够从中请求脚本本身的主机:

var getHost = function() {
  var host = // host from where it has been requested
  return host; // in this case it should return dev.mysite.com
};

How can I accomplish this? 我该怎么做?

I've had difficulty in understanding what you're really after, but you can loop through all the scripts and parse the src . 我很难理解您的实际需求,但是您可以循环浏览所有脚本并解析src

jQuery: jQuery的:

function getHosts(scriptName){
   var hosts  = [];
   scriptName = scriptName.replace(/([.])/g,"\\$1"); // escape special characters

   $('script').each(function(){
      var _src    = this.src;

      if ( RegExp(scriptName).test(_src) ){
         _src = _src.replace(/^https*:\/\//,'');     // remove protocol
         _src = _src.replace(/\/.*$/,'');            // remove rest of path
         hosts[hosts.length] = _src;                 // store it for return
      }
   });

   return hosts;                                     // return results as array
}

alert( getHosts('script.js').join(',') );

And w/o jQuery: 而且没有jQuery:

function getHosts(scriptName){
   var hosts  = [];
   scriptName = scriptName.replace(/([.])/g,"\\$1"); // escape special characters

   var scripts = document.getElementsByTagName('script');
   for (var n=scripts.length;n--;){
      var _src = scripts[n].src;

      if ( RegExp(scriptName).test(_src) ){
         _src = _src.replace(/^https*:\/\//,'');     // remove protocol
         _src = _src.replace(/\/.*$/,'');            // remove rest of path
         hosts[hosts.length] = _src;                 // store it for return
      }
   }

   return hosts;                                     // return results as array
}

alert( getHosts('test.js').join('\n') );

I don't think it's possible without some changes to the way you serve your scripts. 我认为不对脚本的提供方式进行一些更改就不可能实现。 I believe you need to hard code the host name into some variable your script declares, and change that as your script file moves from dev to test to www . 我相信您需要将主机名硬编码为脚本声明的某个变量,并在脚本文件从dev转到testwww test更改。 Alternatively, you can insert the value dynamically using eg PHP. 或者,您可以使用例如PHP动态插入值。

Example: In your script, you'll have something like 示例:在脚本中,您将看到类似

var myscript = {
    // declare a 'namespace'
    stage = '__STAGE_PLACEHOLDER__';

    myfunc = function(args) {
        ...

    }

    // your code goes here
};

Before you serve it, have __STAGE_PLACEHOLDER__ replaced by dev / test / www , and then you can introspect using myscript.stage . 在提供服务之前,将__STAGE_PLACEHOLDER__替换为dev / test / www ,然后可以使用myscript.stage进行内部检查。

If you want the env to depend on the path of the script, not the page which included it, then window.location won't work. 如果您希望环境依赖于脚本的路径,而不是包含脚本的页面,则window.location将不起作用。 What you could do is have a different js script for each env, with a custom getHost() function in it, ie: 您可以做的是为每个环境创建一个不同的js脚本,并在其中添加一个自定义的getHost()函数,即:

var getHost = function () {
  return "dev";
}

To avoid the overhead of having multiple scripts you could generate this additional function on the fly on the server side. 为了避免拥有多个脚本的开销,您可以在服务器端动态生成此附加功能。

You could also ask the user to define the environment himself, ie: 您还可以要求用户自己定义环境,即:

MyApp.config.env = 'dev';

从Mozilla开发人员网站参考window.location

window.location.hostname // the host name (without the port number or square brackets)

暂无
暂无

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

相关问题 SCRIPT5022:集合尚未初始化。 尚未请求或尚未执行请求 - SCRIPT5022: The collection has not been initialized. It has not been requested or the request has not been executed 如何从html页面中选择了某些文本的位置获取div的ID - how to get id of the div from where some text has been selected in an html page Javascript有没有办法检测已请求的页面 - Javascript Is there a way to detect a page has been requested 告诉你包含.php文件的位置? - Tell from where a .php file has been included? 如何读取从php脚本发送的数组的值 - How to read value of an array that has been sent from a php script CORS 策略已阻止从源“null”访问脚本 - Access to Script at ' from origin 'null' has been blocked by CORS policy 萤火虫-如何检测已调用的函数或从何处调用了函数 - firebug - how can I detect what functions have been called or from where a function has been called 如果我只有后台脚本,如何检索已执行上下文菜单的元素? - How to retrieve the element where a contextmenu has been executed if i have only background script? 谷歌脚本说变量之前已经声明过,但我看不到在哪里 - Google script says variable has been previously declared but I do not see where CORS 策略已阻止从原点 '' 在 '' 访问 XMLHttpRequest:没有 'Access-Control-Allow-Origin' header 存在于请求的 - Access to XMLHttpRequest at '' from origin '' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM