I am hosting an apache server where I upload a website to, however it is very slow to deploy (and it is down for a week) so I like testing locally for development. It relies on external files, so I use a --allow-file-access-from-files
tag on my google chrome in order for the JavaScript to run properly.
My problem is that I would like to check whether a file exists before opening in a new tab, and I am having trouble getting that working. I have tried this answer, which works, however it uses JQuery, which I would rather not use. The response in that SO question which doesn't use JQuery is a popular one in multiple questions, however it doesn't appear to work for me. My thought is that it doesn't work for me since it creates a XMLHttpRequest()
which I don't think can access local files.
I know under normal circumstances doing this from JavaScript would be a breach of security and not allowed, however I've never had any problems for my testing ever since I added the --allow-file-access-from-files
tag. Is this possible to do without using JQuery/ajax?
This code is currently working for me, however it uses JQuery
$.ajax({
url:'test.pdf',
type:'HEAD',
error: function()
{
console.log("file doesn't exist");
},
success: function()
{
console.log("file exists");
}
});
While this code does not work, using vanilla JS
function UrlExists(url)
{
var http = new XMLHttpRequest();
http.open('HEAD', url, false);
http.send();
return http.status!=404;
}
if (UrlExists('test.pdf')) {
console.log("file exists");
}
else {
console.log("File doesn't exist");
}
the file test.pdf
does not exist in the proper directory. The JQuery code outputs "file doesn't exist" while the JS code throws an error.