I want to get/set URL of the current page upon certain event.
It seems there are more than one approach for doing it as mentioned in questions/answers below.
Using Jquery
Get URL - $(location).attr('href'); Set URL - $(location).attr('href',url);
Using JavaScript
Get URL - myVar = window.location.href; Set URL - window.location.href = "http://stackoverflow.com";
Which approach works across space-time-browsers-versions?
Get current URL in JavaScript?
How to redirect to another webpage in JavaScript/jQuery?
Answer: Use the window. location. href Property location. href property to get the entire URL of the current page which includes host name, query string, fragment identifier, etc.
You can use the window. location property to access the URL of the current page . If you want to go to a new page , either you can change the href property of history object or call assign method with new url as argument.
There is no way to modify the URL in the browser without reloading the page. The URL represents what the last loaded page was. If you change it ( document. location ) then it will reload the page.
open() to Change Page in JavaScript. The window. open() is a window interface method provided by JavaScript, which loads the specified URL/resource into a new tab or an existing browser with the specified name. This method will generate a new window to open a specified URL.
I don't see any need to use jQuery for this. The following will work perfectly fine in all browsers:
window.location.href = "http://stackoverflow.com";
Or even more simply:
location.href = "http://stackoverflow.com";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With