如何在javascript中获取加载脚本的URL

时间:2018-04-26 15:56:27

标签: javascript

在我的网站mysite.com上,我从anothersite.com加载脚本。有没有办法让mysite.com上运行的脚本知道它是从anothersite.com下载的?

3 个答案:

答案 0 :(得分:0)

我找到了解决方案:

    function serverName() {

    var server = "";

    //IE and EDGE can't use the case-insensitive 'i' in this selector
    var path = $('script[src*="loader.js"]').attr('src'); //Look for the script tag of this script and get the URL

    var regex = RegExp('.*\/\/.*?\/'); // gets this: http://mysite/
    var m = regex.exec(path);
    if (m && m.length) {
        server = m[0].replace(/\/$/, "");//trim trailing slash
    }

    return server;
}

答案 1 :(得分:-1)

hostname

详细了解location.hostname

  

{{1}}属性设置或返回URL的主机名。

答案 2 :(得分:-1)

<!doctype HTML>
    <html>
    <head>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react.min.js" id="know"></script>
        <script>
         const gebi=id=>document.getElementById(id)
         console.log(gebi('know').src)
        </script>
    </head>
    <body>
        Hello
    </body>
    </html>

这样可行