Photo by Frida Bredesen on Unsplash

How do you redirect to another page in Javascript?

Marika Lam

--

There are many ways to redirect to another page. But which is the best?

// 1. window.location
window.location.replace('http://www.example.com')
window.location.assign('http://www.example.com')
window.location.href = 'http://www.example.com'
document.location.href = '/path'

// 2. window.history
window.history.back()
window.history.go(-1)

// 3. window.navigate; ONLY for old versions of Internet Explorer
window.navigate('top.jsp')

// 4. More ways... but probably not a good idea
self.location = 'http://www.example.com';
top.location = 'http://www.example.com';

// 5. jQuery
$(location).attr('href','http://www.example.com')
$(window).attr('location','http://www.example.com')
$(location).prop('href', 'http://www.example.com')

The best way is window.location.replace(...)

window.location.replace(...) is better than using window.location.href

replace() does not keep the originating page in the session history, meaning the user won't get stuck in a never-ending back-button fiasco. window.location.hrefis similar to clicking a link, and replace() is similar to a redirect.

--

--

No responses yet