Reputation: 920
I am attempting to open a local folder by setting window.location.href
to file://folder/
, which I can do in IE, cannot in Chrome.
My goal is to catch
whenever a browser blocks local file access so I can call some other code. Chrome's console is showing me 'Not allowed to load local resource:...' but I am not able to catch it with a try/catch
block
Attempt:
function OpenLocalResource() {
try {
//Fails in Chrome (expected)
window.location.href = 'file://folder/whatever/';
} catch (err) {
//Chrome gives script error 'Not allowed to load local resource:'
//I am expecting to hit this catch block but it does not
alert("Error hit!");
}
}
OpenLocalResource();
How can I detect when a browser does not allow local resource access?
Upvotes: 5
Views: 1118
Reputation: 28722
To see if it's allowed on chrome:
function OpenLocalResource($file) {
var img = $('<img>');
img.load(function() {
console.log(this)
})
img.error(function(err) {
if(err.originalEvent.path[0].currentSrc.length == 0) {
console.log('localfile fail',$file)
}
else {
console.log('regular http/image format fail',$file, err);
// Add here an eventual other check for incase a file DID get loaded, but it's format failed or something.
// Usually you can check via $file == err.originalEvent.path[0].currentSrc
//because chrome will turn C:\userlog.txt into file:///C:/userlog.txt
//whilst http:// image urls will remain the same.
}
})
img.attr('src',$file);
}
OpenLocalResource('C:\\userdata.txt');
OpenLocalResource('http://www.google.com');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Upvotes: 0
Reputation: 5548
Use ajax to test if the file exists before using window.location. I don't believe it is possible to catch the error any other way, because the location is set even with an error, and the JavaScript handler is lost from scope.
var xhr = new XMLHttpRequest();
xhr.open('GET', '/folder/whatever/myfile.html', true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
window.location.href = '/folder/whatever/myfile.html';
} else {
alert("Error hit!");
}
}
};
Upvotes: 0
Reputation: 528
Try this, but you may need to point the image src to an actual image on the client.
function noLocalAccess() {
alert('Error hit!');
}
function OpenLocalResource() {
var myImage=new Image();
myImage.onerror=new Function("noLocalAccess()");
myImage.src='file:///c:/';
window.location.href = 'file://folder/whatever/';
}
OpenLocalResource();
Upvotes: 0
Reputation: 397
It's a security setting, I don't think you can catch it. But you could start chrome using the cmd prompt and adding --allow-file-access.
Upvotes: 1