简体   繁体   中英

How to Trigger a Function when Returning to an HTML5 Page ? (javascript)

I'm going back and forth between two html pages - in my example Page1 and Page 2. When I move back from page 2 to page 1, I want to trigger a rebuild-my-html type function - similar to the way that 'onload' is triggered. Onload, of course, is only triggered when the app has been restarted/reloaded.

I'm not sure if I need to do something before I move to page 2 (an event triggered by the user), or if there is a basic function I can keep for Page 1.

I'm sure this is basic, but I just cannot find it! I have been searching the web for DOM events related to onload.

Basic App Structure

  1. Start on Page 1.
  2. The onload function executes

     function initLoad() 

It is triggered by

      document.addEventListener('readystatechange', function()  

(In real app I Use a javascript onload function to layout some html dynamically)

(In real app, user makes a choices to indicate detail they want to see layed out on Page 2)

  1. User Event button click, moves app to Page 2
  2. On Page 2 an onload function runs

      function init() 

    (In real app, user also initIates some other events)

  3. User event returns app to Page 1 - I'm using

      history.go(-1); 

    because that is the only way I know to do that

  4. Upon returning to Page 1, I WANT APP to Return to Run a rebuild refresh type function

  5. Throughout the use of the app, I WANT the APP to epeatedly go back and forth from Page 1 to Page 2, triggering a refresh functions on both web pages

    (in my real app user is testing themselves on memorization skills. They go back and forth between Page 1 and 2. Page 1 will display information in new ways each time to indicate things that the user has demonstrated knowledge on, in Page 2)

Example Code

Page 1 Code STACKexamplePage1Refresh.html

    <!DOCTYPE html>
    <html>

    <body onunload="OnUnload()">

    </script>

    <script src="STACKExampleRebuild.js"></script>

     <h1> Page 1 </h1>

    <p id = changeMe>Want html info like this to be changed upon return from Page 2 and execution of rebuildExamplePage1 function</p>


    <button onclick="callAnothePage()">Go to Page 2</button>




    <script>
     </script>


    <script>

    function initLoad() {
       alert("Page  1 is loaded");
       console.log ("Page 1 is loaded");

    }

    function OnUnload() { // this does not seem to happen
      alert("Page  1 is UNloaded");
    }


    document.addEventListener('readystatechange', function() {
        // http://stackoverflow.com/questions/14207922/javascript-error-null-is-not-an-object
        if (document.readyState === "complete") {
          initLoad();
        }// end if
      }); // end function

     window.onload = function() { // this is just another way of testing initLoad - it runs too
           alert("*Page  1 is REloaded*");
       }

     function callAnothePage()
     {
        window.location = "STACKexamplePage2Refresh.html"; // 
     }

    </script>

    </body>
    </html>

Page 2 Code STACKexamplePage2Refresh.html

    <!DOCTYPE html>
    <html>
    <body onload="init()">


      <script src="STACKExampleRebuild.js"></script>




    <h1> Page 2 </h1>

    <button onclick="historyBack()">Return To Learn Page</button>


     <script>
    function init() {
       alert("init function executed , Page 2 is loaded");
       console.log ("init function executed , Page 2 is loaded");
    }



    function historyBack() {   
             history.go(-1);
             rebuildExamplePage1(); // this function is in STACKExampleRebuild.js


            //navigator.app.backHistory(); // tried this too .... 1.15.17
            }     



    </script>

    </body>
    </html>

Sample Code: Java Script STACKExampleRebuild.js

     function rebuildExamplePage1(){
        alert("rebuildExamplePage1 function execute .... function  that will allow for Page  1 rebuild executed");
        console.log ("rebuildExamplePage1 function execute .... function  that will allow for Page  1 rebuild executed");

       /*
        var changePage1Info = "This info changed while on page 2";
        document.getElementById("changeMe").innerHTML = changePage1Info;
      */


         }

When I run the rebuildExamplePage1 function, and try to run the commented out part - changing the html id 'changeMe' - which is back on Page 1 -

I get the typical error that "null is not an object " in reference to the changeMe object

I think that is because the javascript function can't access the html on page 1, while it's on page 2 . Though I was hoping that putting the commands after the history command might work.

What I really want is some kind of function that is triggered whenever a user returns to an html page - a refresh/reentry type function

I bet there is some special kind of function, that I have not been able to find, that will execute upon a return to html - like onload does when I first load the page.

A few things I've tried that don't work

The function onUnload for page 1, definitely does not execute at any time - I don't think this makes sense for this example anyway

I found various examples that use persistant data, to pass things to other pages, but they always seem to be pages that have not yet been loaded. I already use persistent data in my onload type functions - but they only happen the first time the page is loaded, not upon return

I need to be able to go back and forth from Page 1 to Page 2

I will have the same problem the second time I return to Page 2. In my real app I bring up different detail info on Page 2 each time

Add IDs to the body tag of each html page, then have a conditional set up to see if the body has the page 2 ID on "load" (I know it's readystatechange, but I cant recreate that in jsfiddle).

 var page2 = document.getElementById('page-2'); if (page2 !== null) { alert('page 2 has been loaded'); } else { alert('page 2 has not been loaded') } 
 <body id="page-2"> </body> 

Okay so after your explanation in the comments on the original question, I think the best solution for you is going to be a pretty simple use of either cookies or localstorage. Either one will work for this scenario, but basically the flow would be something like this:

Page 1 links when clicked would store (either in a cookie or localstorage, I would probably use localstorage if audience browser usage would allow me to do so) what question the user clicked on.

Page 2 would read the store and present the appropriate data to the user.

When the user clicks or enters an answer on Page 2 you can calculate if it is correct or not, save the result to the store, and send the user back to page 1.

Page 1, on load, would need to read the store to determine which items were answered and if they were correct or incorrect.

This is a lot of code to write so I'm not going to actually write it all out, but this should be enough to get you started.

I have my sample app working. Page 1 now returns to it's onload functionality when returning from Page 2. A persistent storage item is also recognized, so I will be able to have a separate set of logic for changing html, when I go back to page 1 after working on page 2 . What I suddenly noticed (and why did I not before?) was that the reason that Page 2 gets reloaded as desired - executing it's onload function- is because Page 1 goes to Page 2 using a direct url reference - which will execute onload functions.

 function callAnothePage()
    {
    window.location = "STACKexamplePage2Refresh.html";  
     }

whereas Page 2 was using 'history' - which meant that onload functionality did not get triggered

  function historyBack() {   
          history.go(-1);

         }     

So two totally different techniques were being used. Certainly seems obvious now, but my attention was always drawn elsewhere. I of course tested to make sure that persistent data would stick around when going back and forth, and it appears to. I was previously sending persistent data from page 1 to page 2, so I figured it would - but you never know until you test.

Using the history could certainly be useful - there are definitely times I might want to do that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM