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.
Related
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.
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
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'm now making a web crawler.
getting a link from HTML is easy part but acquiring a link from the result of javascript is not easy for me.
Can I get the result of javascript so as to know where a link is referred to?
for example.
How can I retrieve the link to google.com from javascript code in Python?
<!DOCTYPE html>
<html lang="en">
<head></head>
<body>
to google
</body>
<script>
document.getElementById('goog').onclick = function() {
window.location = "http://google.com";
};
</script>
</html>
You would need to install node.js and run a separate piece of code that executes the Javascript code in context to emit the html. This is possible using jsdom but the key to it is extracting the Javascript code from the HTML page, and setting up the context correctly.
Python doesn't offer a way to execute the Javascript, which would be a large task, and may not even be what you want, because you won't know how to execute all of the appropriate Javascript.
For the code you showed, you could simply regex the entire thing to get URL-like strings from it, but that could be very ad-hoc and error-prone.
Is there a way to send CoffeeScript to the client's browser and have it compiled to JavaScript there?
<script type="text/coffeescript">
square = (x) -> x * x
list = [1, 2, 3, 4, 5]
squares = (square num for num in list)
</script>
The CoffeeScript compiler is written in JavaScript, so can I send it to the client to compile/run this code in the client's browser?
Jeremy already has this one, but let me add some important details and caveats:
At 39k gzipped (compare to jQuery at 29k), coffee-script.js is a big file; so unless you're actually letting your users run their own CoffeeScript, you really shouldn't use it in production.
As mentioned in the documentation, each CoffeeScript snippet will be in its own anonymous closure. So your example snippet wouldn't do anything—squares wouldn't be visible outside of the script. Instead, you'd want to change it to window.squares = ....
All CoffeeScript code, whether external or inline, will run after all JavaScript code on the page. That's because coffee-script.js doesn't read your <script type="text/coffeescript> tags until after the document is ready, by which time your JavaScripts have already run.
Remote CoffeeScripts are loaded via XMLHTTPRequest, which means that they must be hosted on the same domain as your site. (Certain browsers—Chrome, at least—also have a problem with doing XMLHTTPRequests on file:// paths.)
Currently, the order in which different remote CoffeeScripts run is not guaranteed. I submitted a patch for this, but it's not officially a part of CoffeeScript yet. See this pull request.
So, you might want to look at some alternatives for serving CoffeeScript as compiled JavaScript instead. If you're developing for a Ruby or Python server, there are plugins available. I've tried to list them all at http://github.com/jashkenas/coffee-script/wiki/Web-framework-plugins.
If you're developing a site without a backend, a tool I highly recommend looking at is Middleman, which lets you work with CoffeeScript (as well as Haml and Sass, if you want) during development, then compile and minify it for production deployment.
Perhaps you're looking for this?
"text/coffeescript" Script Tags
While it’s not recommended for serious use, CoffeeScripts may be
included directly within the browser using <script type="text/coffeescript"> tags. The source includes a compressed and
minified version of the compiler (Download current version here, 77k
when gzipped) as
docs/v2/browser-compiler-legacy/coffeescript.js. Include this file
on a page with inline CoffeeScript tags, and it will compile and
evaluate them in order.
The usual caveats about CoffeeScript apply — your inline scripts will
run within a closure wrapper, so if you want to expose global
variables or functions, attach them to the window object.
<script crossorigin src="https://coffeescript.org/v2/browser-compiler-legacy/coffeescript.js"></script>
<script type="text/coffeescript">
square = (x) -> x * x
list = [1, 2, 3, 4, 5]
squares = (square num for num in list)
console.log squares
</script>
The answer is yes. I won't repeat #Trevor's excellent answer, but rather just provide an example of what you're thinking about:
http://forgivingworm.wordpress.com/2010/09/27/running-coffeescript-in-browser/
Basically you
Tag your coffeescript with the text/coffeescript
Include coffee-script.js after all coffeescript on the page (the
compiler will evaluate and compile all coffeescript in order)
Sample HTML below
<html>
<head>
<title>In-Browser test</title>
<script type=”text/javascript” src=”http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js”> </script>
<script type=”text/coffeescript”>
$ -> $(‘#header‘).css ‘background-color‘, ‘green‘
</script>
<script type=”text/javascript” src=”http://github.com/jashkenas/coffee-script/raw/master/extras/coffee-script.js”> </script>
</head>
<body>
<h1 id=”header” style=”color:white”>CoffeeScript is alive!</h1>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>CoffeScript on browser</title>
</head>
<body>
<script type="text/coffeescript">
alert 'It works!'
</script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/coffee-script/1.7.1/coffee-script.min.js"></script>
</body>
</html>
CoffeeScript has to be loaded after the script you want to run.
if using src you must be able to access the file via XMLHTTPRequest, in particular it fails on browsers with file://.