Circumventing Chrome Access-control-allow-origin on the local file system?

前端 未结 3 1557
夕颜
夕颜 2020-12-01 07:38

I\'ve read the other same origin policy topics here on SO, but I haven\'t seen any solutions related to the local file system.

I have a web app (In a loose sense of

3条回答
  •  既然无缘
    2020-12-01 08:30

    Ok, done a lot of fiddling and wasted a lot of time. But I got it figured. The solution in my last answer works fine for Chrome, and for Mozilla. But it does not work for blessed IE, because IE will not fire the onload event: it thinks it has dealt with all the onloads in this file and you can't get it to do another one. However, IE is quite happy to load the file up using the JQuery getScript function (which Chrome will not permit because of the ccess-control-allow-origin policy) -- you will need the JQuery libraries for this to work. So here is what I ended up with:

    function getMyText(){
        var url='mylocalfile.js';
        if (jQuery.support.scriptEval) { 
            var old = document.getElementById('uploadScript');  
            if (old != null) {  
                 old.parentNode.removeChild(old);  
                 delete old;  
                } 
            var head = document.getElementsByTagName("head")[0]; 
            var script = document.createElement('script');
            script.id = 'uploadScript';
            script.type = 'text/javascript';
            script.onload = refresh_page; 
            script.src = url; 
            head.appendChild(script);  
        } else {
           $.getScript(url,function(){
                refresh_page();
          });
         }
    }
    
    function refresh_page() {
        alert(mytext);
    }
    

    In all this, mylocaltext.js defines all my html as the content of a variable, mytext. Ugly, but it works. jQuery.support.scriptEval is true for intelligent browsers that fire onload events if the DOM changes. IE does not, so that sends it to .getScript; Chrome and others do, so that sends them the other way. Anyway this works on local files.

提交回复
热议问题