victorhooi
victorhooi

Reputation: 17275

document.location - Not adding to history

I'm attempting to use document.location(.href) on the onLoad event to redirect from one page (A) to another (B).

From my understanding, if I use document.location.href (as opposed to .replace), it should add (A) to my history. However, this doesn't appear to be happening.

I've tried setting document.location, document.location.href, and using .assign, and none of these seem to add the first page to the history. Is there any JS technique that can be done via onLoad that will cause (A) to be in the history?

Cheers, Victor

Upvotes: 4

Views: 3345

Answers (3)

Alex
Alex

Reputation: 1594

Try:

 location.replace('www.google.com');

This should put the page in your history.

Upvotes: -1

Orr Siloni
Orr Siloni

Reputation: 1308

'location.href', 'document.location' or any of these variations will only add an entry to the browser history if it came from a user initiated action. For example, if user clicks a button that fires a function that performs a 'location.href' it will be added to browser history, but if 'location.href' is called by an onload event - which is not a user initiated action, it will not be added to the history.

Upvotes: 9

SolutionYogi
SolutionYogi

Reputation: 32233

If you modify document.location.href, it will definitely add to the history.

Try this demo page →

Code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<title>Sandbox</title>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<style type="text/css" media="screen">
body { background-color: #000; font: 16px Helvetica, Arial; color: #fff; }
</style>
<script>
$(document).ready( 
function() 
{ 
   $('#hello').click( function(ev) { ev.preventDefault(); document.location.href='http://www.google.com';}); 
} 
);
</script>
</head>
<body>
  <p>Hello from JS Bin</p>
  <a id="hello" href="#">Click Me</a>
</body>
</html>

Can you create a sample page where it shows that browser history is not changed?

Upvotes: 2

Related Questions