Check for newer version of page, and if existing, reload

笑着哭i 提交于 2019-12-12 10:06:50

问题


Basically, I want my page (say page.html) to check if a newer version of page.html exists, and if so, refresh the page, and in doing so, bring up the newer version.

I realize this happens automatically after some time- however, I want this to happen within the time of 30 seconds to 2 minutes.

I'm not sure how this would be accomplished- perhaps some Javascript?

if(/*newer version exists*/) {
location.reload();
}

The part I'm unsure about is how to detect if a newer version exists.

I had an idea for a workaround- have a function that checks if some sort of "signal" has been sent (I'd send it right after modifying a page), and once the "signal" is received, refresh the page.

So far, the only thing I've found is meta refresh. I didn't think of using it before- however, it looks like I might have to.

<META HTTP-EQUIV="refresh" CONTENT="60">

The only issue I have with meta refresh is that it refreshes every minute whether I have a new version of the page or not, which can get very annoying- especially because I have images on the page.

Is it possible to specifically target an element for a meta refresh? (The element being referred to would be a Javascript segment which I frequently modify, and which needs to be up to date)

Update 1 Partial Script: Reloads main.js when the button is pressed. With a few tweaks, I can reload the script every minute or so.

Sandbox

    <button id="refreshButton" onclick="loadScript('/main.js')">
        Refresh script
    </button>


    <script>
        function loadScript(location) {
            var js = document.getElementById("sandboxScript");
            if(js !== null) {
                document.body.removeChild(js);
                console.info("---------- Script refreshed ----------");
            }

            // Create new script element and load a script into it
            js = document.createElement("script");
            js.src = location;
            js.id = "sandboxScript";
            document.body.appendChild(js);
        }
    </script>

回答1:


Basically there is nothing impossible now a days due to availability of WebSockets and easy simple google Firebase messaging or Push messaging. You can very easily send any push message to client page or html app to update itself. or just tell your users to refresh their page. This is available on Chrome, firefox and Safari.

But as you are requesting for simple JS solution, here is what I tried myself as I was having similar need for one of my online admission system project. Although I use PHP in my project, I need html page (to keep minimum server load) to display simple instructions to user. But i found that being a html it get cached by browser and user can not see imp instruction change. So here is my effort to resolve it.

There are 2 part of this.

  1. Client side Javascript &

  2. Server side PHP for checking file modified time.

1. Client Side Javascript

Put this inside somePage.html page that you want to track for changes

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
<!--
$(function() {
console.log( "ready!" );

function CheckNewVersion() {
    var serverFileDate;
    var cachePageDate;

    var cacheFileName = window.location.pathname.split("/").pop();//ge current client file name
    // Document page name is dependant on addressbar URL and for root this might fail. This is simple work around for it.
    if (cacheFileName=="")
    {
        cacheFileName="index.html";
    }
    console.log( "Checking New Version of "+cacheFileName+" on server..." );

    var cachePageDate = document.lastModified; // Check Document Last modified of client page
    var cacheFile = new Date(cachePageDate);// Format to date object
    console.log("Cached File Last Modified: "+cacheFile);



    var jqxhr = $.ajax({//Send file name to script on server to get any change
              method: "GET",
              url: "modify-check.php",
              data: { f: cacheFileName}
            })
          .done(function(data) {
            serverFileDate = data.trim();
            var serverFile = new Date(serverFileDate);
            console.log("Server File Last Modified: "+serverFile);
            if (serverFile>cacheFile)//check for change in modified date.
            {
                console.log('Server has latest version... reload your browser!');
                var ans = confirm("Server has latest version... reload your browser?");
                if (ans == true) {
                    location.reload(true);
                } else {
                    // 
                }
            }else
              {
                  console.log('Everything ok & updated!');
              }
          })
          .fail(function(e) {
            console.log( "error"+e );
          })
          .complete(function() {
            //console.log( "complete" );
            setTimeout(CheckNewVersion, 5000);//check every 5 sec only if complete.
          });
}

setTimeout(CheckNewVersion, 5000);  //check every 5 sec 

    });
//-->
</script>

2. Server Side PHP Script

Put this in modify-check.php file on server to check for given file modified date-time

<?php
//Very simple and self explainatory!
$filename = $_GET['f'];
if (file_exists($filename)) {
    echo date ("m/d/y H:i:s", filemtime($filename));
}
?>

This may not be standard solution but it solved my problem. I hope this is of some help to you!




回答2:


In the end, I found a simpler solution than simply reloading the page.

I linked to some external script (which, in effect, was the only thing I needed reloaded)

I then wrote a little function (I added it to the question), and re-fetched the external script every 10 minutes. Works like a charm, and better yet, isn't visible onscreen, so it doesn't disrupt the user one bit!




回答3:


This is impossible due to the limitations of HTTP. HTTP works in a request/response cycle.

When your page is loaded, you automatically get the newest version on the server. It won't receive a new version without it requesting for one i.e. you can't "push" information down to the client automatically.

What I think you're wanting is the implementation of sockets (Read About Sockets), which is an open port of communication between the server and client that allows for "pushes" from the server.

However, that's implemented on the server-side and may be outside the scope of your project.



来源:https://stackoverflow.com/questions/37601546/check-for-newer-version-of-page-and-if-existing-reload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!