36

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
ClassCastException
  • 1,453
  • 6
  • 15
  • 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

60

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,288
  • 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
  • 14,510
  • 4
  • 35
  • 67
Jinxed
  • 738
  • 7
  • 27