簡體   English   中英

當腳本來自另一個域時獲取 Javascript 域

[英]Getting Javascript Domain When Script Is From Another Domain

我正在編寫一個可以跨域工作的腳本。 我試圖包含來自另一個域的一個腳本,然后讓該腳本包含來自同一域的其他腳本

示例:域 1 - www.mydomain.com

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

示例應用程序 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);

問題是 window.location.host 給出了腳本已下載到的域: www.mydomain.com 。 我想要腳本當前所在的域,在這個例子中是 www.example.com 嗎?

這能做到嗎? 請不要使用 JQuery。

你可以試試這個

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

請注意 document.currentScript 不適用於 IE。

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

通過再次閱讀您的問題,我會簡單地問:

你為什么不這樣做相對於那個 js,說:

imported.src = 'config.js';

它將導入假設為 app.js 兄弟的 config.js

關於評論我為錯誤道歉沒有理解這個問題。

這是一種適用於較新瀏覽器的替代方法,即使使用 dom-adder-injected 腳本也能工作,這些腳本有時不是 getElementsByTagName("script") 集合中的最后一個腳本:

(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?
}());

更新:添加了更全面的支持:在 IE9(s+q)、IE9 中測試為 IE8 (s+q)、FF、Ch

我不知道有什么不同的方法,除了手動嗅探腳本標簽 .SRCs 以匹配硬編碼字符串,哎呀。

快速演示: http : //danml.com/pub/getfilenamedemo2.html鏈接腳本: http : //danml.com/js/filename2.js

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM