Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Want document.open to create a new history element, and back to return to original page

I'm using document.open() + write() + close() to create a new page from the client. This works, but it will replace the current history element with the new page, so when the user clicks back they don't see the page they were just on. Example:

  1. At Home Page
  2. Click button to navigate to page shown below.
  3. Click on the click me button on that page.
  4. Click back - this returns user to home page which I don't want.

I've tried inserting a history element with history.pushState() but that doesn't work either. It allows the document.open page to have a new url. Clicking back returns the user to the URL of the page I want displayed, but it is still the "New Page".

Full HTML page code below. This type of example doesn't work in fiddles but can be tested locally.

<html>
<body>
<button onclick="clickme()">Click me</button>
<script>
function clickme() {
    history.pushState(null, null, "Results/");
    document.open("text/html");
    document.writeln("New Page");
    document.close();
}
</script>
</body>
</html>

Note: Looking for a solution with cross browser support, including the latest Chrome 45 which may has tightened security a bit.

like image 800
Mike Avatar asked Oct 20 '22 03:10

Mike


2 Answers

I did find a workaround but still not exactly what I want.

function clickme() {
    results = window.open();
    results.document.writeln("New Page");
    results.document.close();
}

This obviously makes an entire new tab/window to display the results instead of a new page in the history of the current tab. It is pretty much the same thing in a cell phone since back takes you to the original page, but not on a desktop browser.

like image 68
Mike Avatar answered Oct 28 '22 21:10

Mike


I would create an actual web page for page 3 instead of pushing fake history events.

history.pushState isn't supported in older IE's (9 and below) and is buggy on some Androids, this may not be an issue for your project. http://caniuse.com/#search=history.pushState

If you can't change the back end to redirect to page 3, you could do this in javascript:

  1. save your html in localStorage
  2. redirect to page 3
  3. insert your html when page 3 loads.

page 2:

 function clickme() {
    var html = 'my generated html';
    localStorage.savedHtml = html;
    window.location = 'page3.htm';
 }

page 3:

<html>
<head>
    <!-- I'm assuming you're using jquery -->
    <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
</head>
<body>
<div id="restoredHtml"></div>
<script>
    $(function(){
        var savedHtml = localStorage.savedHtml || 'No html to restore';   
        $('#restoredHtml').html(savedHtml);
        localStorage.removeItem('savedHtml');
    });
</script>
</body>
</html>
like image 24
ProgrammerGuy Avatar answered Oct 28 '22 21:10

ProgrammerGuy