0

Why won't my simple HTML jQuery run on a standard Windows 10 laptop? I've tried Chrome, Firefox and Microsoft Edge. I've checked that Javascript is enabled (it is).

The code below works when I tell it to take the navigation.html directly from the web, but when I want it to take it from my local machine it doesn't work.

Has anyone had a similar problem and found a solution?

<html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>

<body>
  <div id="nav"></div>
  <script>
    $.get("navigation.html", function(data) {
      $("#nav").replaceWith(data);
    });
  </script>
  <p>__1__</p>
</body>

</html>

The code when run on https://codepen.io/pen/ produces the desired output using the full file URL in the $.get (https://raw.githubusercontent.com/mackenziesoftware/jquery-load-page-fragment/master/navigation.html):

My navigation code!

__1__

But when I run this in any of my browsers with the downloaded file (via VS Code), I only get:

__1__

EDIT: I've made a mistake in my initial question and oversimplified the question to try to make it reproducible. So I've actually downloaded the file from GitHub onto my machine, saved it in a folder with my index.html and that is when it won't work. (I can confirm it DOES work when I feed it the file's URL directly from GitHub). Apologies for any confusion!

To confirm, my file structure is as follows:

my_folder:

  • index.html (as per the code snippet)
  • navigation.html *

*downloaded from https://raw.githubusercontent.com/mackenziesoftware/jquery-load-page-fragment/master/navigation.html

The error message I get is:

Access to XMLHttpRequest at 'file:///C:/Users/my_user/my_folder/navigation.html' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, edge, https, chrome-untrusted.
navigation.html:1 
Blithering
  • 560
  • 5
  • 14

1 Answers1

0

Thanks to Ivar's suggestion, I've now realised this is related to/a duplicate of "Cross origin requests are only supported for HTTP." error when loading a local file

Problem was resolved by spinning up a local web server to allow my browser to render local files (which it otherwise was unable to do - for good security-based reasons!)

# Change directory to folder where HTML files are saved
cd C:\Users\my_user\my_folder

# Run local web server
python -m http.server 9000

Navigating to http://localhost:9000 then gave me the result I expected.

Blithering
  • 560
  • 5
  • 14