0

I am looking for a solution with javascript to check if the previous page is not extranal.

With this check I want return true or false so I can use this for another function.

What I have tried is to get the previous URL with history.go(-1) but this is undefined.

I am happy if I can get the previous URL so far.

Hope somebody can help me out with this.

Penny Liu
  • 15,447
  • 5
  • 79
  • 98
Ben
  • 63
  • 1
  • 5

2 Answers2

0

You can use document.referrer to get the URL of the previous page.

To check whether it is external or not, you can parse it with the URL constructor and compare its origin.

const previousURL = document.referrer;

const isPreviousURLExternal = new URL(previousURL).origin == new URL(location).origin;
console.log(isPreviousURLExternal)
Spectric
  • 30,714
  • 6
  • 20
  • 43
0

Simply use to know previous URL

document.referrer

 document.write(document.referrer);
GMKHussain
  • 3,342
  • 1
  • 21
  • 19