Asked 2 years ago
20 May 2021
Views 11309
yogi

yogi posted

How to get or print the previous URL in JavaScript ?

i am tracking history of the url so when user click back button it goes to the previous and also i need to store that url by ajax

sec8

sec8
answered Nov 30 '-1 00:00


window.history.back()

it will lead browser to previous page.



window.history.go(-1)

window.history.go(-1) also redirect browser to previous page . also window.history.go(-2) will redirect backward 2 pages


you cant store the complete previous URL because there is no function for that
you can use

document.referrer;

which will give you the domain name only of the previous url if you are using a desktop browser, and maybe it gives the full URL if you using the mobile browser
but this work only if it referred, i mean it should be coming by a href click, if you use the back button of the browser or directly type URL at browser then document. referrer is an empty string .
so i think it not useful for your case.
jabber

jabber
answered Apr 14 '22 00:00

window.history.back() will redirect to the previous URL so you cant print it
window.history.go(-1) will redirect to the previous URL so you cant print it
document.referrer will give you the site page where you come at this page

console.log(document.referrer)

will print the previous url . but it prints empty if no previous url.
Post Answer