Get full url from hyperlink using jQuery / JavaScript

How can I get the full URL at which anchor links using jQuery / JavaScript appear sequentially in all browsers? For example, I want to return http://www.mysite.com/mypage.aspx from <a href="../mypage.aspx"></a> .

I tried the following:

  • $(this).attr('href') : The problem is that jQuery returns the exact value of href (i.e. ../mypage.aspx ).

  • this.getAttribute('href') : This works in Internet Explorer, but in FireFox it behaves the same as above.

Which alternative? I canโ€™t just add the current site path to the href value, because this will not work in the above case, in which the href value is executed in the current directory.

+6
source share
1 answer

You can create an img element and then set the src attribute to the extracted href value. Then, when you get the src attribute, it will be fully qualified. Here is an example that I used from http://james.padolsey.com/javascript/getting-a-fully-qualified-url/ :

 function qualifyURL(url){ var img = document.createElement('img'); img.src = url; // set string url url = img.src; // get qualified url img.src = null; // no server request return url; } 
+5
source

Source: https://habr.com/ru/post/902517/


All Articles