简体   繁体   中英

Current Page URL in a hyperlink

In the code below, I am hard coding the url.

<a class="button_link" href="https://somewebsite.com/submit/?url=http%3A%2F%2Fsomecrazyurl.com" target="_blank" aria-label="Sharei">

Instead I want something like this:

<a class="button_link" href="https://somewebsite.com/submit/?url=returnpageurl()" target="_blank" aria-label="Sharei">

Edit: For the record I used

$(location).attr('href');

However nothing gets returned.

Is there any cross-browser Javascript to return the current url of the page?

To get the path, you can use:

  var pathname = window.location.pathname; // Returns path only
  var url      = window.location.href;     // Returns full URL

You can use jQuery's attribute selector for that.

var linksToGoogle = $('a[href="http://google.com"]');

Alternatively, if you're interested in rather links starting with a certain URL, use the attribute-starts-with selector:

var allLinks = $('a[href^="http://google.com"]');

If you are looking for a browser compatibility solution use

window.location.href 

where document.URL is having issues with Firefox with reference to this

<a class="button__link" href="#" target="_blank" aria-label="Sharei" id="current_url">Current URL</a>

This is simple to use as below with no complexity ,the thing what I found is you are not assigning any value to the href attribute and by default in jquery it assigns back

https://somewebsite.com/submit/?url=returnpageurl()

Now the below one should work for your case,

 $("#current_url").attr("href",window.location.href );

This is easy to achieve by using the window.location.href JavaScript window property.

Html Example:

<a href="https://somepage.com" id="link1">my link</a>

Javascript

var a = document.getElementById('link1');
a.href = a.href + '?returnUrl=' + encodeURIComponent(window.location.href);

With jQuery:

$('#link1').attr('href', $('#link1').attr('href') + '?returnUrl=' + encodeURIComponent(window.location.href));

Note the use of the built in function encodeURIComponent(str) reference.

The encodeURIComponent() function encodes a Uniform Resource Identifier (URI) component by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two "surrogate" characters).

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