31

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?

Community
  • 1
  • 1
Ganesh Bhosle
  • 1,363
  • 6
  • 14
  • 34
  • To change the URL without redirecting the page use [`history.replaceState`](https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState), which [works on all major browsers](https://caniuse.com/mdn-api_history_replacestate). – Dave F Apr 21 '21 at 17:27

2 Answers2

56

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";
meub
  • 2,228
  • 17
  • 19
5

I agree with @meub . this will also do :

window.location.replace("http://stackoverflow.com");

To behave as clicking a link you need to use simple javascript . You don't need jQuery for doing that. You can use the following:

Get URL - myVar = window.location.href;
SET URL - window.location.href = "http://stackoverflow.com";
Fildor
  • 12,873
  • 4
  • 34
  • 64
Jinxed
  • 738
  • 6
  • 27
  • 1
    window.location.replace as as good as redirect I guess. I mean it is not like clicking on a link, but like being redirected. – Ganesh Bhosle Aug 23 '13 at 07:00