The first method attempts to duplicate the function of the back button.
The second method takes whatever the browser claims is the URI of the previous page, put it in the page without sanitizing it, and attempts to run the URI as if it was JavaScript. This promptly errors because URIs are very rarely valid JavaScript.
The better approach would be to work out the URI you want to go to (presumably based on the data that you used to build the current page with) and create a normal forwards pointing link (<a href...
) to it … and let the user use the built in back button in their browser if they want to go back. This approach:
- Won't fail if JS isn't available
- Won't fail if their browser doesn't send an optional HTTP header
- Won't confuse users by making their browser's history work in unexpected ways
I'm not certain, but I suspect there is a risk that someone could craft a URI and put a link on it to your page, including "<script>...
in it. A user could then click on that link, get the URI of the page they came from inserted into the page, and introduce you to an XSS attack. (I think this should fail because some of those characters should be URI encoded, but I wouldn't want to risk it — always put in the standard protections against XSS whenever you have data coming from outside your system and back into your page)