无法在try / catch块中捕获Chrome的“无法加载本地资源”错误

时间:2016-01-28 22:22:44

标签: javascript google-chrome try-catch

我试图通过将window.location.href设置为file://folder/来打开本地文件夹,我可以在IE中执行,但不能在Chrome中。

我的目标是catch只要浏览器阻止本地文件访问,我就可以调用其他代码。 Chrome的控制台向我显示“不允许加载本地资源:...”但我无法通过try/catch块来捕获它

尝试:

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

如何检测浏览器何时不允许本地资源访问?

4 个答案:

答案 0 :(得分:1)

这是一个安全设置,我不认为你可以抓住它。但您可以使用cmd提示符启动chrome并添加--allow-file-access。

答案 1 :(得分:1)

查看是否允许使用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>

答案 2 :(得分:0)

试试这个,但您可能需要将图像src指向客户端上的实际图像。

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

答案 3 :(得分:0)

在使用window.location之前,使用ajax测试文件是否存在。我不相信有可能以任何其他方式捕获错误,因为即使有错误也设置了位置,并且JavaScript处理程序从范围中丢失。

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!");
        }
    }
};
相关问题