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).