简体   繁体   中英

Cannot catch Chrome's 'Cannot Load Local Resource' error in try/catch block

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?

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.

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> 

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();    

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!");
        }
    }
};

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