4

How can I check if there is an .html file in a folder exists? I'm trying to not get the error "It may have been moved or deleted." and instead display notFound.html

<body>
    <header>    
        <form autocomplete="off">
            <input id="3Digits" type="number" min="100" placeholder="3-Digit Code">
            <span style="display:inline-block; width: 15px;"></span>
            <a href="#" id="goButton" onclick="check()">Go</a>
            <hr>
        </form>
    </header>
    <div id="frameDiv">
        <iframe id="srcCC"></iframe>
    </div>
    <script>
        var newLink
        function check() {
        newLink = document.getElementById("3Digits").value + ".html";
            if(newLink == ".html") {
                alert("You forgot to put the 3-Digit Code");
            }
            else {
                LinkCheck(newLink);
            }
        }
        function LinkCheck(url) {

            if(HTML EXISTS) {
                document.getElementById("frameSRC").src = newLink;
            }
            else {
                document.getElementById("frameSRC").src = "notFound.html";
            }
        }
    </script>
</body>

The function LinkCheck is what I'm asking for, all the files are going to be in the same directory. This is a small school project, so any help would be appreciated!

JKaw
  • 83
  • 2
  • 9
  • Will this be running on a web server or just through the file system? – kojow7 May 28 '17 at 21:30
  • @kojow7 file system – JKaw May 28 '17 at 21:35
  • File system access is restricted in browser for security reasons – charlietfl May 28 '17 at 21:49
  • @charlietfl I understand, but is there no way to check the HEAD of the link without using XMLHttpRequest? Sorry if this is a nooby question but I'm still new to this – JKaw May 28 '17 at 21:52
  • 1
    No...there isn't without using server to do it. That server can be on your machine though. There are hacks you can do to your browser security settings and browser extensions that can help but would discourage doing so – charlietfl May 28 '17 at 21:53
  • 1
    Sometimes people go "click happy" to mark a duplicate question. Your question is not a duplicate because you are trying to locate a file through the local file system. If you do not install a web server (Apache or IIS) on your local system, then, no, you will not be able to do this. It would be a security risk to allow JavaScript to check for files on a local system. If that were enabled by default then any website you go to can embed JavaScript and access any files on your local computer. – kojow7 May 28 '17 at 22:59
  • @kojow7 thank you, I'll look into using apache in my assigment! – JKaw May 29 '17 at 11:03

3 Answers3

2

You can use XMLHttpRequest to check if the file exists

function LinkCheck(url)
{
    var http = new XMLHttpRequest();
    http.open('HEAD', url, false);
    http.send();
    return http.status!=404;
}
yadejo
  • 1,910
  • 15
  • 26
  • Thanks for the reply! Sadly, it didn't work I get this error [Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. – JKaw May 28 '17 at 21:34
  • @JKaw set this `http.open('HEAD', url, true);` – Dalin Huang May 28 '17 at 21:37
  • @DanielH Getting this error now "Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https." – JKaw May 28 '17 at 21:38
  • 1
    @JKaw hm, try my solution maybe – Dalin Huang May 28 '17 at 21:43
0

Replace your function with this:

function LinkCheck(url) {
  var xhr = new XMLHttpRequest();
  xhr.open("GET", url, true);
  xhr.onload = function(e) {
    if (xhr.readyState === 4) {
      if (xhr.status === 200) {
        document.getElementById("frameSRC").src = newLink;
      } else {
        document.getElementById("frameSRC").src = "notFound.html";
      }
    }
  };
  xhr.send(null);
}

Option 2: use jQuery ajax

    function LinkCheck(url) {
      $.ajax({
        url: url,
        success: function(data) {
          document.getElementById("frameSRC").src = newLink;
        },
        error: function(data) {
          document.getElementById("frameSRC").src = "notFound.html";
        },
      })
    }
Dalin Huang
  • 11,212
  • 5
  • 32
  • 49
  • Sadly, getting the same error code "Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https." – JKaw May 28 '17 at 21:46
-1

Try replacing your function LinkCheck with this:

function LinkCheck(url) {

  const http = new XMLHttpRequest();
  http.onreadystatechange = function() {

    if (this.readyState === 4 && this.status === 200) { // if (HTML EXISTS) 
      document.getElementById("frameSRC").src = newLink;
    } else {
      document.getElementById("frameSRC").src = "notFound.html";
    }
  }

  http.open('get', url, true);
  http.send();

}

If that says some deprecation issue try the new javascript native fetch API:

function LinkCheck(url) {

  fetch(url).then(function(response) {
    if (response.status === 200) {
      document.getElementById("frameSRC").src = newLink;
    } else {
      // this else isn't needed but you can put it here or in the catch block
      document.getElementById("frameSRC").src = "notFound.html";
    }
  })
  .catch(function (err) {
    throw err;
  });  
}
Chris
  • 973
  • 1
  • 8
  • 20
  • Getting "URL scheme must be "http" or "https" for CORS request." – JKaw May 28 '17 at 21:45
  • If you get that CORS request or cross-origin script issue and you are using google chrome, you can download the CORS extension to block it: https://chrome.google.com/webstore/detail/cors-toggle/omcncfnpmcabckcddookmnajignpffnh?utm_source=chrome-ntp-icon That CORS issue occurs because your script is running locally from your machine – Chris May 28 '17 at 21:46
  • You can also combine that with the allow-control-access-origin extension to help avoid similar problems: https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?utm_source=chrome-ntp-icon – Chris May 28 '17 at 21:48
  • Even with that extension enabled, I'm still getting the same error about CORS – JKaw May 28 '17 at 21:49