How to redirect the user to another Javascript/jQuery page?

Asked

Viewed 141,141 times

27

I would like to know what methods of redirecting exist in Javascript, and also using jQuery, and if possible, I would like to know all of them.

4 answers

61


In this case jQuery is not necessary.
The solution goes through simple javascript.
Here are two options:

Option 1:

window.location.href = "http://answall.com";
// ou uma variante com o mesmo efeito
window.location.assign("http://answall.com");

Option 2:

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

The difference between these two methods is that the first makes it possible to click back on the browser history and go to the previous page. The second replaced the current page and when clicking to go back in history, the homepage is not accessible (it has been replaced in the story).


If you want the user to open a new window (without losing the source window), you can use:

window.open("http://answall.com");

This method open window.() also allows passing parameters/options such as size, content, etc.

  • 1

    great answer, I will mark as correct.

  • 4

    location.replace is great (preventing the history.back) for authenticated areas, preventing the user from returning to the login screen without disconnecting. And it is also very useful in applications that use webViews (example: Ios, android). + 1 for your answer!

  • @Guilhermenascimento, good example, I fully agree.

9

Via jQuery (only for knowledge if desired)

$(location).attr('href', 'http://www.sitedesejado.com');

However, as already mentioned, it is not necessary jQuery to perform redirection.

  • Value mention that .prop()/.attr() are designed to work with DOM elements only. Passing other types of objects is asking to have a headache in the future. =]

8

With javascript even:

window.location.href = "http://seusite.com"

3

As mentioned above just use the command:

window.location="http://seusite.com";

no need for the href, minimizing your code.

  • Uncaught (in Promise) Typeerror: window.Location is not a Function

Browser other questions tagged

You are not signed in. Login or sign up in order to post.