簡體   English   中英

無法在try / catch塊中捕獲Chrome的“無法加載本地資源”錯誤

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

我試圖通過將window.location.href設置為file://folder/來打開本地文件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(); 

如何檢測瀏覽器何時不允許本地資源訪問?

這是一個安全設置,我認為你不能抓住它。 但您可以使用cmd提示符啟動chrome並添加--allow-file-access。

要查看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> 

試試這個,但你可能需要將圖像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();    

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM