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

Eri*_*ips 5 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();
Run Code Online (Sandbox Code Playgroud)

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

Tsc*_*cka 0

要查看 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');
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Run Code Online (Sandbox Code Playgroud)