javascript require doesn't work inside html - javascript

I'm writing html code that involves js code. Below a simple example:
<!DOCTYPE html PUBLIC >
<html>
<body>
<h2>Use JavaScript to Change Text</h2>
<p>This example writes "Hello JavaScript!" into an HTML element with id="demo":</p>
<p id="demo"></p>
<script>
var net = require('net');
var sleep = require('sleep');
var element = document.getElementById("demo");
element.innerHTML = "Hello JavaScript!";
sleep(1)
</script>
Unfortunately "Hello JavaScript!" doesn't appear when I browse the above file with my browser. Looking inside the debug console I can see the folowing message:
ReferenceError: require is not defined
So it seems that require is not defined inside the html code but I've written a small test.js file as below:
var net = require('net');
var sleep = require('sleep');
sleep.sleep(1)
and then I run it with
node test.js.
No errors, everything works fine, require is available and sleep and net as well. Why the code inside html file doesn't work?

Javascript is not the same as node.js
require() is not a part of JavaScript standard and is not supported by browsers out of the box, it is the node.js module system.
You might need to directly include the modules; some of the modules might not work in the browser sandbox context.
Also, tools such as http://browserify.org/ might be useful.

The reason you are getting ReferenceError: require is not defined is because nowhere in your html page is Require included. Require does not come with your standard JavaScript library. You must include the file on your page so it can be loaded and used.
This can be done by simply adding <script src="myJS.js"></script> in the <head> or <body> tags. The myJS.js file will, of course, be replaced by the require.js file.
The reason it works when you run with node is because Node already has its own module loader.

Related

cannot manipulate dom object after nodejs require statement

I am trying to learn nodejs and I cannot manipulate DOM object after using the require statement in server.js file. However, it works fine without it. When I click on the paragraph in the browser it would not change. Does anyone know why?
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
</head>
<body>
<p id="demo">Click me to change my HTML content (innerHTML)</p>
<script src="server.js"></script>
</body>
</html>
server.js
var config = require('./config');
document.addEventListener('DOMContentLoaded', function() {
$("#demo").click(function () {
document.getElementById("demo").innerHTML = "Paragraph changed!";
})
});
If you are running your server file using node, document is not going to reference your browser. Your browser is unavailable to Node. Only front-end javascript is going to be able to reference the DOM. In addition, using require in front-end javascript should throw an error if you're not using some bundler such as browserify and therefore the following jQuery code will not run. Open up your browser's developer tools and you should see an error in the console.
Node is not meant to work with the DOM and server files shouldn't be inserted into your HTML. Keep your server code separate from your front-end code. Node is meant to set up servers and serve up files, not to work with the DOM. Try reading more about Node and what it's used for, and maybe do a few tutorials to get familiar with it.
Open the html in the browser, consle say require is not defined
at server.js:1. In html script not support the require syntax

Using Document object in nodejs

I'm still new to javascript and node.js and was trying to accomplish something but I am encountering the error ReferenceError: Document not defined
Given the following code in seperate files:
Index.html:
<!DOCTYPE html>
<html>
<head>
<title>My Test Website</title>
<script type="text/javascript" src="script.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body>
<p id="para1"> Some text here</p>
</body>
</html>
And script.js:
function getParagraphContents() {
var paragraph = document.getElementById("para1");
var temp = paragraph.textContent;
console.log(temp);
}
So my problem being is I wanted to be able to run the command node script.js from the command line but keep getting an error message. I keep reading other answers and documentation but nothing seems to be the right answer. Any suggestions? P.S. I am using terminal on mac osx and have node and npm install correctly.
Thank you.
script.js is a script designed to run in a browser, not in node.js. It is designed to operate on the current web page and uses the document object to get access to that page.
A node.js execution environment is not the same as a browser. For example, there is no notion of the "current page" like there is in a browser and thus there is no global document or window object either like there is in a browser.
So, this all explains why trying to run node script.js doesn't work. There's no global document object so your script quickly generates an error and exits.
We can't really tell from your question if you just don't really understand the difference between running scripts in a browser vs. running scripts in a node.js environment and that's all you need to have explained or if you actually want to operate on an HTML document from within node.js?
It is possible to operate on HTML pages from within node.js. The usual way to do that is to get an HTML parsing library like jsdom. You can then load some HTML page using that library and it will create a simulated browser DOM and will make things like the document object available to you so you could execute a browser-like script on an HTML document.

inject figwheel's or boot's cljs-repl to arbitrary webpages

Could the leiningen plug-in figwheel or boot's counterpart be used within arbitrary webpages? I'm thinking of it as an replacement of the browser's builtin developer console.
Here is a simple scenario of how I'd imagine this workflow:
You open an arbitrary website in the browser. Beside that, you have a browser repl inside a terminal window, which is provided by one of the tools mentioned above. (I guess they both use 'weasel' for this.)
Inside the terminal one could access the current state of the weppages' DOM.
E.g: (set! (.. js/window style backgroundColor) "green"))
I guess this should not be too problematic to archive. However, I faced the following problems:
Both tools do actually just inject a bunch of JavaScript into the users's HTML page. It's basically: The users's ClojureScript compiled to JavaScript plus additional implementation of the hot-reloading mechanism via websockets. The second is just omitted when the project comes into production.
My idea was to just inject the whole bundle to another page.
I used boot for the try.
After setting up the boot's ClojureScript REPL, I opened localhost:port in a browser. It's inital source looks like this:
<!doctype html>
<html>
<head>
<title>Hello, World!</title>
</head>
<body>
<script src="js/main.js"></script>
</body>
</html>
The after main.js has been executed on page-load, many (more than 100) further javaScript tags are injected to the page. My initial idea was to just open another page now, say duckduckgo.com, and inject that one script tag to it, augmented with an absolute path to localhost.
so, at the duckduckgo.com page, inside the developer console I did this:
tag = document.createElement("script");
tag.src = "http://localhost:3000/js/main.js";
document.body.appendChild(tag);
As expected the script gets injected, and this always leads to the immediate execution of its code. I was expecting that all the other script tags get injected now automatically. Finally the webSockets should be connected to the ClojureScript repl.
However, there's the following error in the browser console: A call to document.write() from an asynchronously-loaded external script was ignored.
Indeed, many of the further script tags have been injected. But not all of them. Effectively, the socket connection is not established.
So, it looks like some script tags are injected by the mechanism I used myself (via appendChild), others should be done by document.write("<script... The later causes the problem here.
Does anybody know a way to archive this?

I can't run javascript on notepad++

So I found online javascript tutorials and I downloaded notepad++ to write my code. The problem is that I can't run it. I tried saving it as .html and then running it with mozilla but then I got the whole code written into the mozilla window.
I mean if the code is
var x = 5;
console.log(x);
I get this whole thing written there, not executed.
JavaScript needs to be in a <script> tag for a HTML file:
<script>
var x = 5;
console.log(x);
</script>
You can also define the JavaScript in a .js file and reference it by doing:
<script src="myJSFile.js"></script>
In that case you don't need to place <script> tags inside the .js file.
Maybe you are not showing file extension in windows, and you think that you are saving it in "index.html" but you are saving as "index.html.txt" and mozilla opens it as a text file

How to access JavaScript module pattern in my case?

I have defined the following module in MyModule.js:
MyModule.js:
MyModule = {
controller: {
paintCar: function(color){
//PAINTING PROCESS
}
},
tester: {
...
},
};
Then, I have another javascript file, other.js:
other.js:
MyModule.controller.paintCar('red');
My index.html
<body>
<script scr="MyModule.js"></script>
<script src="other.js"></script>
</body>
All these files are put under WebContent directory of Eclipse Dynamic Web Project.
In other.js when I try to run the above code, I got error "MyModule is not defined". Why?
You misspelt src here: <script scr="MyModule.js">. This would have been picked up by basic automated QA testing.
(Original answer before the theory was confirmed) Presumably, because you aren't loading the script files properly. Since you haven't shown us the code that does that (or even told us what environment you are using) it is hard to say exactly how you went wrong.
Assuming you are using client side JS in a webpage, your code should look something like:
<script src="MyModule.js"></script>
<script src="other.js"></script>
Order is significant. End tags are mandatory. Self-closing tag syntax is unacceptable (unless the document is served as application/xhtml+xml)
(This uses HTML 5 syntax. For HTML 4 / XHTML 1, add a type attribute. For HTML 3.2, add a language attribute)
You haven't mentioned your environment, but generally you have to ensure that the JavaScript in MyModule.js is executed before the JavaScript in other.js, because you need MyModule.js to set up the MyModule variable.
How you do it will vary by environment. In a web browser, you'd do that by putting in two script tags, first one for MyModule.js then the one for other.js (although frequently, for use on websites, you want to have a build process that combines your scripts into a single file to minimize HTTP requests). In NodeJS, there's the whole require mechanism.
Update based on your edit:
Looks like a typo:
<body>
<script scr="MyModule.js"></script>
^^-- here, they're transposed
<script src="other.js"></script>
</body>
If that typo isn't really in your file, then look to see that the files are where the web server expects, that the web server isn't being thrown by capitalisation, that sort of thing. Fundamentally, that's correct.

Categories