11

The code below works well. Here is my problem: The window url redirects, but the original url is not logged in my browser history.

For example, if I visit "http://example.com/page1", the browser redirects to "http://example.com/test", as it should. However, I need the original url visited ("http://example.com/page1") to show up in my browser history so that I can call upon it in a different function.

Is there anyway to get the original url visited to log in my browser's history before redirecting?

<!-- script to enable age verification cookies and ensure people have age checked -->
<script type="text/javascript">
    $(document).ready(function(){
       if (window.location =="http://example.com/home") {//do nothing
       } else {
           window.location = "http://example.com/test";
       }
    });
</script>
user1546779
  • 121
  • 1
  • 2
  • 6
  • what about saving it in a global variable before changing the location? Or you could `window.open` with a target of `_self` or `_top` – MrOBrian Jul 23 '12 at 21:11
  • I might pass it in the hash or the query string. – Blazemonger Jul 23 '12 at 21:27
  • sorry, but im a bit of an amateur when it comes to jquery/javascript...how would I save it as a global variable or target window.open as a _self or _top? And would using one of those two methods prior to redirecting ensure that the original url was saved in the browser's history? many thanks for helping out a newb – user1546779 Jul 23 '12 at 22:59
  • @MrOBrian I just tried this, and it didn't work either. for some reason it won't load the original url into the browser's history... `window.open('http://www.example.com/test','_self','', false);` – user1546779 Jul 23 '12 at 23:40
  • What browser are you trying? I just tested in Chrome and using window.open left my previous page in the history. According to Microsoft documentation, the 4th parameter is `replace`, so having it false should add to the history in IE (at least, maybe others), and a quick test in Firefox also let me go back after doing a window.open – MrOBrian Jul 24 '12 at 00:01
  • @MrOBrian I checked it in Chrome and Safari. Neither of them saved the original url in the history. Here is another look at my code...do you notice anything else that could cause this to happen? `` – user1546779 Jul 24 '12 at 00:36
  • Could it possibly be a problem with how I'm calling the history? Here is my other function (within a form): `
    `
    – user1546779 Jul 24 '12 at 00:37

3 Answers3

5

I think what you need is window.location.href. This adds the previous URL to the browser history.

Silver Gonzales
  • 694
  • 5
  • 6
  • 3
    Reading elsewhere, it sounded like setting window.location was essentially the same as setting window.location.href. Is there a documented difference? – Cincinnati Joe Oct 30 '13 at 12:54
2

I came across this behavior myself and it was because I was loading pages into chrome via the filesystem, i.e. using the file:// protocol. I started an HTTP server, and using that got it to keep the history.

1j01
  • 3,714
  • 2
  • 29
  • 30
1

tl;dr, just show me the code

var newUrl = "https://example.com.page2";

// Navigate to newUrl, adding a new entry to the Browser History
window.location.assign(newUrl);
window.open(newUrl, "_top");

JavaScript Browser Navigation With History

There are at least two methods to navigate (redirect) while retaining browser history. With Vanilla JavaScript, one of these are likely what we're looking for:

  1. Easiest: window.location.assign() - part of the Location object in the Browser Window API.
  2. Most Powerfull: window.open() - part of the Browser Window API. window.open() is far more powerful than location.assign() - as it can affect not just the current browser tab, but can also be used within an <iframe>, control which browsing context (a tab, window or iframe) to control, as well as change window features - including options such as the window's default size and position, whether to open a minimal popup window, and so forth.

Keep in mind that window.open() has caveats and usability/user experience issues, as it can open Popups - the exact same popups that most browsers block (Chrome, Firefox) because advertisers / spammers abuse(d) the functionality provided by window.open(). It's still a viable API to use, when used properly.

Browser History can also be managed and controlled directly via the Browser History API, including reading from, modifying existing, and adding new history entries. The History API however does not control navigation, and cannot be used for redirection. It's very often used with Single Page Applications, such as AngularJS, React, Vue.js, Svelte, etc.

Most of the text / descriptions below are directly sourced from MDN Web Docs. Please see the included links for more information. I have slightly modified the descriptions and examples from the MDN API Reference to be more relative to the question asked.

window.location.assign()

Source / Reference: https://developer.mozilla.org/en-US/docs/Web/API/Location/assign

The window.location.assign() method causes the window to load and display the document at the URL specified. After the navigation occurs, the user can navigate back to the page that called window.location.assign() by pressing the "back" button.

If the assignment can't happen because of a security violation, a DOMException of the SECURITY_ERROR type is thrown. This happens if the origin of the script calling the method is different from the origin of the page originally described by the Location object, mostly when the script is hosted on a different domain.

If the provided URL is not valid, a DOMException of the SYNTAX_ERROR type is thrown.

window.location.assign() Syntax

window.location.assign(url)

window.location.assign() Parameters

url: Is a string containing the URL of the page to navigate to.

window.location.assign() Example

var newUrl = "https://example.com.page2";

// Navigate to newUrl, adding a new entry to the Browser History
window.location.assign(newUrl);

window.open()

Source / Reference: https://developer.mozilla.org/en-US/docs/Web/API/Window/open.

⚠️ NOTE: I've only included a VERY small amount of information related to the extremely versitile window.open() method. I highly recommend you review the full documentation for window.open().

The open() method of the Window interface loads a specified resource into a new or existing browsing context (that is, tab, window, or <iframe>) under a specified name.

window.open() Syntax

open()
open(url)
open(url, target)
open(url, target, windowFeatures)

window.open() Parameters

url: Optional

A string indicating the URL or path of the resource to be loaded. If an empty string ("") is specified or this parameter is omitted, a blank page is opened into the targeted browsing context.

target: Optional

A string, without whitespace, specifying the name of the browsing context the resource is being loaded into. If the name doesn't identify an existing context, a new context is created and given the specified name. The special target keywords, _self, _blank, _parent, and _top, can also be used.

This name can be used as the target attribute of <a> or <form> elements.

windowFeatures: Optional

A string containing a comma-separated list of window features in the form name=value — or for boolean features, just name.

⚠️ NOTE: See the window.open() syntax for the full reference of Window Features.

window.open() Return value

A WindowProxy object. The returned reference can be used to access properties and methods of the new window as long as it complies with Same-origin policy security requirements.

window.open() Description

The Window interface's open() method takes a URL as a parameter, and loads the resource it identifies into a new or existing tab or window. The target parameter determines which window or tab to load the resource into, and the windowFeatures parameter can be used to control the size and position of a new window, and to open the new window as a popup with minimal UI features.

Note that remote URLs won't load immediately. When window.open() returns, the window always contains about:blank. The actual fetching of the URL is deferred and starts after the current script block finishes executing. The window creation and the loading of the referenced resource are done asynchronously.

window.open() Basic Example

For answering the question, the minimal form of window.open() to browse to a new URL, in the same browser tab, retaining browser navigation history.

var newUrl = "https://example.com/page2";

// Navigate to newUrl, adding a new entry to the Browser History
window.open(newUrl, "_top");
Rick B
  • 91
  • 2
  • 4