Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

306
Visualizações
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
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda