I'm trying to use a javascript variable that is rendered on the client in my Node script, but Node keeps saying the variable is undefined. Here is the code:
test.js
const express = require('express');
const jsdom = require("jsdom");
const { JSDOM } = jsdom; // it exports a JSDOM class
var app = express();
app.get('/', function(req, res) {
res.sendFile('url_grabber.html', {root: __dirname })
});
app.listen(3000); //port
// Create "your" server
const local = express()
.use('/', (req, res) => {
JSDOM.fromURL('http://localhost:3000/', {
runScripts: "dangerously", resources: "usable" // allow <script> to run
}).then((dom) => {
// pass back the result of "target_url" from the context of the
// loaded dom page.
res.send(dom.window.target_url);
console.log(url_string);
});
})
.listen(3001);
url_grabber.html
<!DOCTYPE html>
<html>
<body>
<p>Enter your URL to download: <input type="text" id="url_string" value=""></p>
<button onclick="saveUrl()">Click Me!</button>
<script>
function saveUrl() {
var target_url = document.getElementById("url_string").value
console.log(target_url)
document.getElementById('url_string').value = '' //clears text box
}
</script>
</body>
</html>
The node script crashes when I laod the page served on port 3001. I don't really want anything to be served apart from my HTML, but that's what the example I found on SO suggested. Note if I in-line basic HTML, then the code works, as described here: node.js parsing html text to get a value to a javascript variable
That example works, but my HTML is too large to effectively inline (unless i use JSDOM serialize maybe?)
I'd prefer to keep the HTML/JS in a seperate file for ease of reading if possible.