简体   繁体   中英

why is this a cross domain request

I'm trying to make a set of files to be able to send to someone and they can view some stuff in a web browser locally. My code works when viewed using a web server(apache) but if I load it up just as a file, (ie file:///C:/Code/Web/test/index.html) it get a cross domain request error from my JavaScript file when loading a JSON file. The HTML, JS, and JSON files are all in the same folder. I'm not sure how this is a cross domain request and why chrome and IE fail at loading the JSON file. Firefox loads it without problem.

The JS I use for loading the file is:

const JSON_FILE = "tin.json";
var xmlhttp;

function webGLStart() 
{
    fetchDoc(JSON_FILE,loadJSON)
}

function fetchDoc(url,cfunc)
{
    if (window.XMLHttpRequest)
    {
        xmlhttp=new XMLHttpRequest();
    }
    xmlhttp.onreadystatechange=cfunc;
    xmlhttp.open("GET",url,false);
    xmlhttp.send();
}

function loadJSON()
{
    if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
    {
        var input = JSON.parse(xmlhttp.responseText);
        displayData(input);
    }
}

Nothing really happens in my html page. Its just a canvas where the body calls webGLStart on load.

Is there a way around this or is this something chrome and IE don't allow?

It protects you from attacks such as ones of this form:

  • You receive an email with an HTML document as an attachment
  • You double click the attachment and open the HTML document in your default browser
  • JavaScript embedded in the document accesses files on your hard disk and uploads them to the attacker

Chrome and IE ban the access of file scheme URIs outright. Firefox allows them only if the host URI is in a directory that is a ancestor of the directory contains the target URI.


You've already identified the way around it: Host web applications on a web server.

Browsers have to restrict interaction with local file system due to security reasons. If you want to test your ajax request, you can set up light http server environment such as lighttpd, node.js npm package http-server or use one of development solutions, such as Microsoft WebMatrix

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