Cross-origin request for local file
Asked Answered
F

6

19

I need to open a local html file in the browser. The javascript works fine but ajax stops working and XMLHttpRequest gives a cross origin error. Is there a way to run ajax from local directory. It is necessary for me that it is run from local file only.

Thanks

Fracture answered 19/4, 2017 at 10:37 Comment(1)
Possible duplicate of XmlHttpRequest error: Origin null is not allowed by Access-Control-Allow-OriginUnexacting
F
15

For anyone who wants to know, I had to run a server in the app to serve the js files. Seems like it's not possible to do it without running a server. If anyone knows of another way, do tell.

Fracture answered 28/1, 2018 at 14:14 Comment(3)
Some reference on what this means and how to do it would help.Manikin
For anyone else seeking an easy way to do this, I can open html files locally and preview their contents within Visual Studio Code, when VSCode is loaded as an administrator.Unsought
For those wanting an easy solution to get up and running in 5 minutes, the following sites were handy: github.com/lwsjs/local-web-server/wiki/… OR timnwells.medium.com/… (I used the Python section)Outdistance
H
3

The simplest way to allow this in Firefox is to navigate to about:config, look for the privacy.file_unique_originsetting and toggle it. Its value should read 'false' now.

Essentially, Firefox used to treat local files from the same directory as being from the same source, thus CORS was happily satisfied. That behavior changed after CVE-2019-11730 was discovered.

It worked fine for me on 84.0.1 on Arch. Just be sure to turn it on again when not locally debugging.

Source

Hobbledehoy answered 30/12, 2020 at 3:13 Comment(6)
I would not recommend turning this on and off. The accepted answer is the proper way to deal with this issueInstallment
did not work for me. @KerwinSneijders why should I fire up a webserver for a quick local test, especially for a simple HTML file that includes some JS? Unnecessary complexity for a simple task...Tranship
@Tranship If you can be 100% sure you always turn it back on afterwards it's... okay... I guess. But turning off security features like this should never be recommended.Installment
@KerwinSneijders that might be true if there is a “correct” way; e.g. a way to edit policy. There does not appear to be a correct way.Dahna
Support for setting 'privacy.file_unique_origin' seems to have been dropped starting with Firefox 95 (released december 2021). Advice by Mozilla is: "Developers who need to perform local testing should now set up a local server."Frequent
I had to toggle security.fileuri.strict_origin_policy to make it work.Simplicidentate
W
1

If you are using VS Code, the Live Server extension might help you. It resolved a cross-origin issue I was having when editing a webpage.

https://marketplace.visualstudio.com/items?itemName=ritwickdey.LiveServer

Wallas answered 25/1, 2021 at 5:5 Comment(0)
F
0

Here's a local HTML-file that raises a cross origin error when executing an XMLHttpRequest.

<!DOCTYPE html>
<html>
    <body>
        <h2>Using the XMLHttpRequest Object</h2>
        <div id="demo">
            <button type="button" onclick="loadXMLDoc()">Change Content</button>
        </div>
        <script>
          function loadXMLDoc() {
            var xhttp = new XMLHttpRequest();
            xhttp.onreadystatechange = function() {
              if (this.readyState == 4 && this.status == 200) {
                document.getElementById("demo").innerHTML =
                this.responseText;
              }
            };
            xhttp.open("GET", "https://itcorp.com/", true);
            xhttp.send();
          }
        </script>
    </body>
</html>

Getting it to work

Advice for running ajax requests from your local machine:

Install a lightweight webbrowser. No need to install a webserver.

Nothing happens

When using a modern browser, the console in the developer tools shows an error: | Error | | - | | Access to XMLHttpRequest at "https://itcorp.com/" from origin "null" has been blocked by CORS policy: No "Access-Control-Allow-Origin" header is present on the requested resource. |

Instead of influencing or disabling the protective mechanism your web browser, we want to use a browser that has limited protection whilst browsing the web.

How to pick a web browser

Using website 'AlternativeTo' I found an alternative to Google Chrome webbrowser: Falkon.

Falkon is available for Windows and Linux.

1. Modern browser
When opening your local HTML-file in Chrome:
Clicking the button is possible but nothing happens.
2. Lightweight browser
When opening your local HTML-file in Falkon:
Clicking the button is possible and content is changed.

Disclaimer

Requesting resources from (evil) websites is dangerous! All modern browsers will block these type of requests. In 2011 a specification was designed for it based on the 'same-origin' concept (RFC 6454). Modern browsers implemented protective functionality and forced it to end users as a policy.

  • For example Google Chrome:
    • 2010: CORS functionality introduced
    • 2020: Stricter CORS policies begin gradually rolling out.
    • 2023: Stricter CORS policies are now the standard.

As a developer you may want to use a lightweight browser for browsing local files. You should be careful in NOT using this browser for browsing the internet!

Testing

  • Tested the local HTML-file in Falkon using version 3.1.0 (March 2019).
Frequent answered 15/12, 2023 at 11:13 Comment(0)
U
-2

If you are using chrome, try this extension

CORS allows web applications on one domain to make cross domain AJAX requests to another domain. It's dead simple to enable, only requiring a single response header to be sent by the server.

What this extension does is add to response header rule - Access-Control-Allow-Origin: *

You can do that manually also by sending a response header.

For simple CORS requests, the server only needs to add the following header to its response: Access-Control-Allow-Origin: *

Read this for more info.

Ulysses answered 19/4, 2017 at 10:47 Comment(3)
Actually I am using android webview.Fracture
You can do it manually also, the server only needs to add Access-Control-Allow-Origin: * header to its response.Ulysses
I can't see, how does it answers the question.Zitella
A
-2

If you are able to change the server code, you can try adding the string "null" to allowed origins. In Chrome, it sends the origin as "null" if it's running from a local file.

Here's an example in ASP.NET Core for setting up the "null" origin:

services.AddCors(options =>
{
    options.AddPolicy("InsecurePolicy",
        builder => builder
            .WithOrigins("null")
            .AllowAnyMethod()
            .AllowAnyHeader()
            .AllowCredentials());
});

Note that this is not recommended, but might be good enough if you just need it during development.

Auspicious answered 13/2, 2020 at 3:8 Comment(1)
There's no server involved in loading HTML from the local filesystem.Eth

© 2022 - 2024 — McMap. All rights reserved.