Как найти url скрипта

I include myscript.js in the file http://site1.com/index.html like this:

<script src=http://site2.com/myscript.js></script>

Inside “myscript.js”, I want to get access to the URL “http://site2.com/myscript.js”. I’d like to have something like this:

function getScriptURL() {
    // something here
    return s
}

alert(getScriptURL());

Which would alert “http://site2.com/myscript.js” if called from the index.html mentioned above.

Eric Leschinski's user avatar

asked Jun 4, 2010 at 18:13

MikeC8's user avatar

4

From http://feather.elektrum.org/book/src.html:

var scripts = document.getElementsByTagName('script');
var index = scripts.length - 1;
var myScript = scripts[index];

The variable myScript now has the script dom element. You can get the src url by using myScript.src.

Note that this needs to execute as part of the initial evaluation of the script. If you want to not pollute the Javascript namespace you can do something like:

var getScriptURL = (function() {
    var scripts = document.getElementsByTagName('script');
    var index = scripts.length - 1;
    var myScript = scripts[index];
    return function() { return myScript.src; };
})();

answered Jun 4, 2010 at 18:22

lambacck's user avatar

lambaccklambacck

9,7223 gold badges33 silver badges46 bronze badges

18

You can add id attribute to your script tag (even if it is inside a head tag):

<script id="myscripttag" src="http://site2.com/myscript.js"></script>

and then access to its src as follows:

document.getElementById("myscripttag").src

of course id value should be the same for every document that includes your script, but I don’t think it is a big inconvenience for you.

answered Aug 8, 2011 at 12:04

tsds's user avatar

tsdstsds

8,63012 gold badges62 silver badges83 bronze badges

2

Everything except IE supports

document.currentScript

answered Aug 24, 2016 at 13:05

dave1010's user avatar

dave1010dave1010

15.1k7 gold badges67 silver badges64 bronze badges

3

Simple and straightforward solution that work very well :

If it not IE you can use document.currentScript
For IE you can do document.querySelector('script[src*="myscript.js"]')
so :

function getScriptURL(){
 var script =  document.currentScript || document.querySelector('script[src*="myscript.js"]')
 return script.src
}
update

In a module script, you can use:

 import.meta.url

as describe in mdn

answered Jul 9, 2017 at 15:06

pery mimon's user avatar

pery mimonpery mimon

7,5226 gold badges51 silver badges56 bronze badges

I wrote a class to find get the path of scripts that works with delayed loading and async script tags.

I had some template files that were relative to my scripts so instead of hard coding them I made created the class to do create the paths automatically. The full source is here on github.

A while ago I had use arguments.callee to try and do something similar but I recently read on the MDN that it is not allowed in strict mode.

function ScriptPath() {
  var scriptPath = '';
  try {
    //Throw an error to generate a stack trace
    throw new Error();
  }
  catch(e) {
    //Split the stack trace into each line
    var stackLines = e.stack.split('n');
    var callerIndex = 0;
    //Now walk though each line until we find a path reference
    for(var i in stackLines){
      if(!stackLines[i].match(/http[s]?:///)) continue;
      //We skipped all the lines with out an http so we now have a script reference
      //This one is the class constructor, the next is the getScriptPath() call
      //The one after that is the user code requesting the path info (so offset by 2)
      callerIndex = Number(i) + 2;
      break;
    }
    //Now parse the string for each section we want to return
    pathParts = stackLines[callerIndex].match(/((http[s]?://.+/)([^/]+.js)):/);
  }

  this.fullPath = function() {
    return pathParts[1];
  };

  this.path = function() {
    return pathParts[2];
  };

  this.file = function() {
    return pathParts[3];
  };

  this.fileNoExt = function() {
    var parts = this.file().split('.');
    parts.length = parts.length != 1 ? parts.length - 1 : 1;
    return parts.join('.');
  };
}

answered Mar 4, 2014 at 7:10

QueueHammer's user avatar

QueueHammerQueueHammer

10.4k12 gold badges67 silver badges91 bronze badges

7

if you have a chance to use jQuery, the code would look like this:

$('script[src$="/myscript.js"]').attr('src');

answered Aug 14, 2013 at 3:03

Mr. Pumpkin's user avatar

Mr. PumpkinMr. Pumpkin

6,1205 gold badges44 silver badges59 bronze badges

3

Following code lets you find the script element with given name

var scripts = document.getElementsByTagName( 'script' );
        var len = scripts.length
        for(var i =0; i < len; i++) {
            if(scripts[i].src.search("<your JS file name") > 0 && scripts[i].src.lastIndexOf("/") >= 0) {
                absoluteAddr = scripts[i].src.substring(0, scripts[i].src.lastIndexOf("/") + 1);
                break;
            }
        }

answered Apr 2, 2014 at 5:54

Varun Bhatia's user avatar

Varun BhatiaVarun Bhatia

4,30631 silver badges44 bronze badges

1

document.currentScript.src

will return the URL of the current Script URL.

Note: If you have loaded the script with type Module then use

import.meta.url

for more import.meta & currentScript.src

answered Apr 23, 2021 at 19:34

Airy's user avatar

AiryAiry

5,3247 gold badges51 silver badges77 bronze badges

Some necromancy, but here’s a function that tries a few methods

function getScriptPath (hint) {
    if (  typeof document === "object" && 
          typeof document.currentScript === 'object' && 
          document.currentScript && // null detect
          typeof document.currentScript.src==='string' && 
          document.currentScript.src.length > 0) {
        return document.currentScript.src;
    }
    
    
    let here = new Error();
    if (!here.stack) {
        try { throw here;} catch (e) {here=e;}
    }
    if (here.stack) {
        
        const stacklines = here.stack.split('n');
        console.log("parsing:",stacklines);
        let result,ok=false;
        stacklines.some(function(line){
            if (ok) {
               const httpSplit=line.split(':/');
               const linetext = httpSplit.length===1?line.split(':')[0]:httpSplit[0]+':/'+( httpSplit.slice(1).join(':/').split(':')[0]);
               const chop = linetext.split('at ');
               if (chop.length>1) {
                   result = chop[1];
                   if ( result[0]!=='<') {
                      console.log("selected script from stack line:",line);               
                      return true;
                   }
                   result=undefined;
               }
               return false; 
            }
            ok = line.indexOf("getScriptPath")>0;
            return false;
        });
        return result;
    }
    
    if ( hint && typeof document === "object") {
       const script = document.querySelector('script[src="'+hint+'"]');
       return script && script.src && script.src.length && script.src;
    }
    
}
   
   console.log("this script is at:",getScriptPath ())

answered Jul 12, 2021 at 11:17

unsynchronized's user avatar

unsynchronizedunsynchronized

4,8192 gold badges31 silver badges43 bronze badges

Can’t you use location.href or location.host and then append the script name?

answered Jun 4, 2010 at 18:16

Paul's user avatar

PaulPaul

2,69920 silver badges26 bronze badges

2

This method work with defer, async and lazy loading
Since you know the filename of your script, and if it will be unique

/* see  
 * http://stackoverflow.com/questions/984510/what-is-my-script-src-url/984656#984656
 * http://www.glennjones.net/Post/809/getAttributehrefbug.htm
 * 
 * iterate all script to find script with right filename
 * this work with async and defer (but your script MUST have a unique filemane)
 * mozilla support document.currentScript and we use it, if is set
 *
 * this will not work with local script loaded by jQuery.getScript(),
 * since there is no script tag added into the dom. the script is only evaluated in global space.
 * http://api.jquery.com/jQuery.getScript/
 *  
 * to fix this odd, you can add a reference in meta ( meta[name=srcipt][content=url] )
 * when you load the script
 */
var scriptFilename = 'jquery.plugins.template.js'; // don't forget to set the filename 
var scriptUrl = (function() {
    if (document.currentScript) { // support defer & async (mozilla only)
        return document.currentScript.src;
    } else {
        var ls,s;
        var getSrc = function (ls, attr) {
            var i, l = ls.length, nf, s;
            for (i = 0; i < l; i++) {
                s = null;
                if (ls[i].getAttribute.length !== undefined) { 
                    s = ls[i].getAttribute(attr, 2);                    
                }               
                if (!s) continue; // tag with no src
                nf = s;
                nf = nf.split('?')[0].split('/').pop(); // get script filename
                if (nf === scriptFilename) {
                    return s;
                }
            }
        };          
        ls = document.getElementsByTagName('script');
        s = getSrc(ls, 'src');
        if ( !s ) { // search reference of script loaded by jQuery.getScript() in meta[name=srcipt][content=url]
            ls = document.getElementsByTagName('meta');             
            s = getSrc(ls, 'content');
        }           
        if ( s ) return s;
    }
    return '';
})();

var scriptPath =  scriptUrl.substring(0, scriptUrl.lastIndexOf('/'))+"/";

a jquery plugin template with it:
https://github.com/mkdgs/mkdgs-snippet/blob/master/javascript/jquery.plugins.template.js

note: this will not work with local script loaded by jQuery.getScript(), since there is no script tag added into the dom. the script is only evaluated in global space.
http://api.jquery.com/jQuery.getScript/

to fix it you can do something like:

function loadScript(url,callback) {     

    if ( $('[src="'+url+'"]').length ) return true; // is already loaded    

    // make a reference of the loaded script
    if ( $('meta[content="'+url+'"]', $("head")).length ) return true; // is already loaded 
    var meta = document.createElement('meta');
    meta.content = url;
    meta.name = 'script';
    $("head").append(meta);

    return $.ajax({
          cache: true,
          url: u,
          dataType: 'script',
          async: false,
          success : function (script) {                     
                try { 
                    if ( typeof callback == 'function' ) callback();    
                } catch (error) { 
                    //console.log(error);
                }
          }
     });
}

Как получить url текущей страницы на JavaScript

Рассмотрим как получить URL текущей страницы в JS целиком, а также по отдельности — протокол, доменное имя сайта, GET параметры и значение после решётки (хеша). Полная информация об адресе содержится в объекте «document.location». Доступ к отдельным элементам получаем через его свойства.

Разберём адрес: https://realadmin.ru/saytostroy/?page=4#top
Свойство Значение
document.location.href https://realadmin.ru/saytostroy/?page=4#top
document.location.protocol https:
document.location.host realadmin.ru
document.location.pathname /saytostroy/
document.location.search ?page=4
document.location.hash #top

Получение значений GET параметров

Javascript предоставляет специальный объект для работы с GET параметрами. С его помощью можно проверить существование параметра по названию и получить значение.

Для примера возьмем адрес:

https://realadmin.ru/saytostroy/?page=4&limit=10&sortby=desc

Извлечём значения «page» и «sortby»:

var paramsString = document.location.search; // ?page=4&limit=10&sortby=desc  
var searchParams = new URLSearchParams(paramsString);
    
searchParams.get("page"); // 4
searchParams.get("sortby"); // desc

URLSearchParams — объект не доступен в устаревших версиях браузеров, например во всех версиях IE.

Для проверки существования параметров, воспользуйтесь методом «has».

searchParams.has("limit"); // true
searchParams.has("sortby"); // true
searchParams.has("orderby"); // false

Для перебора всех пар ключ/значение используем метод «entries».

for(var pair of searchParams.entries()) {
   console.log(pair[0]+ ', '+ pair[1]); 
}

Результат:

  • page 4
  • limit 10
  • sortby desc

Разбор URL из строки

Кроме всех вышеприведённых примеров, можно воспользоваться объектом URL.

var addr = new URL('https://realadmin.ru/saytostroy/?page=4&limit=10&sortby=desc#top');
Свойство Значение
addr.href https://realadmin.ru/saytostroy/?page=4#top
addr.protocol https:
addr.host realadmin.ru
addr.pathname /saytostroy/
addr.search ?page=4&limit=10&sortby=desc
addr.hash #top

Интересно, что этот объект содержит свойство «searchParams» типа «URLSearchParams», который можно использовать для извлечения GET параметров.

var addr = new URL('https://realadmin.ru/saytostroy/?page=4&limit=10&sortby=desc#top');

if (addr.searchParams.has('limit')) {
    let limit = addr.searchParams.get('limit'); // 10
}

Объект Location связан с адресной строкой браузера, в его свойствах содержатся все компоненты URL доступные для чтения и записи.

Доступ к Location обычно осуществляется через объекты Document.location или Window.location. Если скрипт запускается из iframe (в одном домене), доступ к родительскому окну доступен через window.parent.location.

Рассмотрим какие будут значения при следующим URL:

http://www.example.com/pages/contats?page=1&sort=2#marker

1

Location.href

Вернет полный URL страницы.

console.log(window.location.href);

JS

Результат:

http://www.example.com/pages/contats?page=1&sort=2#marker

Объекту location можно присвоить новый URL, браузер сразу перейдет на новую страницу.

window.location.href = 'https//snipp.ru';

JS

Так же для редиректа можно использовать методы location.assign() и location.replace(). Отличие последнего в том, что пользователь не сможет использовать кнопку «назад».

window.location.assign('https//snipp.ru');

JS

window.location.replace('https//snipp.ru');

JS

2

Location.protocol

Возвращает используемый протокол, включая :.

console.log(window.location.protocol);

JS

Результат:

http:

3

Location.port

Номер порта, если его нет в URL, то ни чего не выведется.

console.log(window.location.port);

JS

4

Location.host

Содержит домен и порт (если есть).

console.log(window.location.host);

JS

Результат:

www.example.com

5

Location.hostname

Содержит только домен.

console.log(window.location.hostname);

JS

Результат:

www.example.com

6

Location.pathname

Строка пути текущий страницы, начинается с /.

console.log(window.location.pathname);

JS

Результат:

/pages/contats

7

Location.search

GET-параметры, начинается с ?.

console.log(window.location.search);

JS

Результат:

?page=1&sort=2

8

Location.hash

Хеш страницы, начинается с #.

console.log(window.location.hash);

JS

Результат:

#marker

Для изменения хеша не обязательно указывать решетку:

window.location.hash = '123';

JS

Чтобы получить url страницы, можно воспользоваться глобальным объектом window.location. Этот объект содержит свойство href, которое содержит адрес текущей страницы.

Например:

const currentUrl = window.location.href;
console.log(currentUrl); // => https://ru.hexlet.io/qna

Некоторые другие свойства объекта window.location:

  • href – весь URL
  • protocol – протокол URL
  • host – имя хоста и порт URL
  • hostname – имя хоста URL
  • port – номер порта
  • pathname – путь в URL (та часть, которая идёт после первого слэша /)
  • search – часть запроса URL (та часть, которая идёт после знака вопроса ?)
  • hash – часть URL (та часть, которая идёт после знака решётки #)

Добавить комментарий