This is extremely basic but I'm unsure why this has stopped working. I have the following html file
<html>
<!doctype html>
<head>
<script> document.write("this is working")</script>
<p>this is working</p>
</head>
<body>
<script src="test.js"></script>
</body>
</html>
and the following javascript file that is in the same folder as the html file
document.write("Hello World!");
The scripts and html within the html document work fine. However, the external javascript file does not get executed. I have tried with a variety of scripts in the js file and minor modifications to the html file. On a windows 10 computer.
Note this is not a repeated question, the other questions similar to this one were slightly different.
EDIT: Error in browser console states "not allowed to load local source" This may be a chrome security issue. EDIT: Same case in all browsers so doesn't seem purely related to chrome. Attempted all the fixes I could find but did not work.
EDIT: I tried using both node and python for the server.
CodePudding user response:
Looks like you're loading the HTML file through file protocol (i.e. double-clicking the file and opening it in a browser). In that case, browser may deny to load any external resources (test.js
script in your case) due to security. Load the HTML through HTTP protocol. It can be achieved numerous ways.
- If you have PHP installed, simply running
php -S localhost:80
within the project directory will spin up a local server, which you can browse by visitinghttp://localhost
. It will then serve theindex.html
page by default. - If you have Node.js installed (thus
npm
, too), installhttp-server
globally (npm i http-server -g
). And afterthat, runhttp-server
within the project directory. By default, it will spin up a local server on port8080
, so you'll be able to visithttp://localhost:8080
andindex.html
will be served.
I tried the later one, and your above code worked perfectly fine.
CodePudding user response:
This is not a solution, but it is a work around if anyone has the same issue and a better answer is not produced.
Get the chrome extension "web server" and open that rather than running it through node, python, etc.