Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

305
Views
Cannot parse javascript variable from local file using jsdom & express

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.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!