-->

How to get/set current page URL (which works acros

2020-08-09 06:08发布

问题:

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?

回答1:

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


回答2:

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