Reputation: 1275
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?
Upvotes: 0
Views: 1559
Reputation: 659
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"]');
Upvotes: 1
Reputation: 949
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
Now the below one should work for your case,
$("#current_url").attr("href",window.location.href );
Upvotes: 1
Reputation: 12683
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).
Upvotes: 0