Current Page URL in a hyperlink - javascript

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?

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 );

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"]');

This is easy to achieve by using the window.location.href JavaScript window property.
Html Example:
my link
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).

Related

how to get page url without decode in javascript?

How can I get page URL from window.location.href without decode in javascript?
For example we can not get exactly this URL: http://example.com/report#title=example_report&url=project_chart%2F%3Fproject_id%3D77.
When we use window.location.href in javascript , we will get this URL:
http://example.com/report#title=example_report&url=project_chart/?project_id=77.
But I want to get exactly the same real URL.
Any solution?
Edited
as #Eugenio told, $(document)[0].URL works fine , but Is it safe?!
Try to use encodeURI.
As for example;
var url = window.location.href;
var originalUrl = encodeURI(url);
This function(encodeURI) encodes special characters,
except: , / ? : # & = + $ #
You can use encodeURIComponent() to encode these characters.
You can use encodeURIComponent, but you have to get the part of a string you want to encode.
encodeURIComponent(window.location.href.split('&url=')[1])
Or you can use RegExp to be more precise.
Just to make a clear and concise answer I will sum up all the comments.
For your problem the best solution is to use document[x].url where x is the index of the URL part that you want to use.
The main difference for your problem between window.location.href and document.url is that the last one gives you the URL in a string format, whilest the other return the URL already parsed.
Using either one is completely normal and safe and is widely adopted in all modern browsers.
var url1 = document.URL;
var url2 = window.location.href;
document.getElementById("documentUrl").append (url1);
document.getElementById("windowLocationUrl").append (url2);
<div id="documentUrl">document.url: </div>
<div id="windowLocationUrl">window.location.href: </div>
There is no difference in this particular snippet example because there are no parameters attached to the URL. Anyway, hope this helped. Cheers!
as #Eugenio told,
i use below code and it works fine:
var url = $(document)[0].URL;

javascript location href changed queryString (&gt to >)

I have the following code in my page.
<script>
var url = "http://localhost/login.aspx?returnUrl=/ABC/abc.aspx&gt_no=1234567&code=SC";
window.location.href = url;
</script>
when i load the page, it redirect to
http://localhost/login.aspx?returnUrl=/ABC/abc.aspx>_no=1234567&code=SC
the parameter &gt_no changed to >_no
Is there any method to keep &gt_no remain unchange after redirect?
It is not allow to use other parameter name insteand of &gt_no in my project.
The problem not just happen in localhost.
Thanks!
You have arrived at a situation where you have generated an HTML encoded value value even though you didn't mean to :)
&gt is the HTML encoded value for the greater than character - >. You could try make sure that your gt_no parameter is the first parameter. This way, it will not be next to the ampersand (&) character and won't be interpreted as a HTML encoded value.
You could try URL Encoding the ampersand that is causing the issue:
var url = "http://localhost/login.aspx?returnUrl=/%26gt_no=1234567&code=SC";
var url = "http://www.google.com/login.aspx?
returnUrl=/ABC/abc.aspx&gt_no=1234567&code=SC";
window.location.href = url;

How to get the parts of a url using document.referrer?

I need to use document.referrer to get the previous URL I also need to be able to get the parts of the URL like:
window.location.protocol
window.location.host
window.location.pathname
but I can't figure out how to do it with document.referrer. Anyone got any ideas?
You can create an a element with the referrer as its url.
a elements (with hrefs) can act like location objects
var a=document.createElement('a');
a.href=document.referrer;
alert([a.protocol,a.host,a.pathname].join('\n'));
a='';
There's no equivalent to window.location with regards to document.referrer so your only option will be to break down the string itself. You could write a regex to do that or rely on a series of string splits:
var parts = document.referrer.split('://')[1].split('/');
var protocol = document.referrer.split('://')[0];
var host = parts[0];
var pathName = parts.slice(1).join('/');
If you want the convenience and can afford the weight, have a look at URI.js or one of the suggested URL parsers. If you don't need anything fancy, <a>s href decomposition will do the job just fine.

How to remove part of the URL within window.location?

I have fetched window.location into a variable. Now, I want to remove part of the string from the href within the location object, but still retain the object.
In other words, I want to modify the location object, and still be able to use window.location.protocol and window.location.host, but those functions need to work on the modified object.
For example, something like this where my browser displays "https://my.domain.org/site":
var thisloc = window.location;
Modify the href within that object to "http://my.domain.org/othersite"
//now I want it to fetch "http" instead of "https" based on my modified object
var thisprot = thisloc.protocol;
Will that work? If it does, it would be very nice. Otherwise, I have to parse the URL to get the protocol, host and pathname from a modified href, which would also accomplish the same goal.
Inspired by James Padosley's post on Parsing URLs with the DOM!, the trick here is to use an anchor element (<a>) as a URL builder/parser. With any anchor element, if you set its href property to some URL, it will be parsed by the DOM. Thereafter, you can freely modify the parts of that URL via properties on the anchor element. Query the href property at any time to see the full URL.
Using the example from the question…
var builder = document.createElement("a");
builder.href = "https://my.domain.org/site";
builder.protocol = "http://";
builder.pathname = "/othersite";
console.log(builder.href); // http://my.domain.org/othersite
At this point the anchor element's href will now be http://my.domain.org/othersite, as requested. Here's a JS Bin demonstrating it in action: http://jsbin.com/omoqen/1/edit.
The beauty is that anchor elements have the same URL component properties as the window.location object:
protocol
host
hostname
port
pathname
search
hash
These are browser properties - you can fetch and modify the values, but referring to the property won't work in the way you describe.

Getting the #id from current URL

I'm looking for a way to retrieve the #anchor part from the current URL with JavaScript.
For example:
http://my-page.com/index.html#contact-us
Would return contact-us.
I could split the URI at the eventual # and then take the last piece, but I'm looking for a somewhat nicer and cleaner suggestion. A native (jQuery?) function would be great, but I guess I'm asking for too much.
Use location.hash:
location.hash.slice(1);
It starts with a #, hence .slice(1). Given an arbitrary string, you can use the built-in URL-parsing feature by creating a <a> element, and set the href, then read other properties, such as protocol, hostname, hash, etc. jQuery example:
$('a').attr('href', url)[0].hash;
location.hash.replace(/^#/, "")
If you work with a variable:
var url = "http://my-page.com/index.html#contact-us";
var hash = url.substring(url.indexOf("#") + 1);

Categories