简体   繁体   中英

Getting Javascript Domain When Script Is From Another Domain

I am writing a script that is suppose to work across domains. I trying to include one script from another domain and then have that script include other scrips from the same domain

Example: Domain 1 - www.mydomain.com

<html>
    <head>
       <script type="text/javascript" src="http://www.example.com/app.js"></script>
    </head>
</html>

Example App JS

var imported = document.createElement('script');
imported.src = window.location.host + 'config.js';
document.head.appendChild(imported);

var imported = document.createElement('script');
imported.src = window.location.host + 'stuff.js';
document.head.appendChild(imported);

The problem is window.location.host gives the domain that the script has been download to: www.mydomain.com . I wanted the domain that the script currently resides on, which is in this exmaple is www.example.com ?

Can this be done? And please no JQuery.

You can try this

if (document.currentScript && document.currentScript.src) {
    var uri = new URL(document.currentScript.src);
    includeJsFile(uri.origin + '/static/script.js');
}

Please note that document.currentScript does not work on IE.

https://caniuse.com/#search=document.currentScript

By reading your question again i would simply ask:

why dont you do that relatively to that js, say:

imported.src = 'config.js';

it will import the config.js that suppose to be a brother of app.js

regarding to the comments i apologise for mistake didnt understood the question.

here is an alternate method for newer browsers that works even with dom-adder-injected scripts, which sometimes are NOT the last script in a getElementsByTagName("script") collection:

(function(){ // script filename setter, leaves window.__filename set with active script URL.
if(self.attachEvent){
 function fn(e,u){self.__filename=u;}
 attachEvent("onerror",fn);
 setTimeout(function(){detachEvent("onerror", fn)},20);
 eval("gehjkrgh3489c()");
}else{
 Object.defineProperty( window, "__filename", { configurable: true, get:function __filename(){
   try{document.s0m3741ng()}catch(y){
    return "http://" + 
     String(y.fileName || y.file || y.stack || y + '')
     .split(/:\d+:\d+/)[0].split("http://")[1];
    } 
 }})//end __filename
}//end if old IE?
}());

UPDATE: more comprehensive support added: TESTED IN IE9(s+q), IE9 as IE8 (s+q), FF, Ch

i don't know of a different way, other than manually sniffing script tag .SRCs to match a hard-coded string, yuck.

quick demo: http://danml.com/pub/getfilenamedemo2.html linked script: http://danml.com/js/filename2.js

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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