Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why addEventListener doesn't work in jsdom module for nodejs

I use the following code to call some stuff after clicking by an element on a page

var http = require('http');
var fs = require('fs');
var jsdom = require('jsdom');

http.createServer(function(req, res) {

    res.writeHead(200, {'Content-Type': 'text/html; charset=utf8'});
    var document = new jsdom.JSDOM('<!doctype html><html><head></head><body><p>Text</p></body></html>').window.document;
    document.getElementsByTagName('p')[0].addEventListener('click', function() {
        alert('OK');
    });     
    var page = '<!doctype html><html>'+document.getElementsByTagName('html')[0].innerHTML+'</html>';
    res.end(page);

}).listen(80, 'localhost');

But if I click the paragraph, nothing happens

I read the answer by the link https://stackoverflow.com/a/36804251/10587062 but I didn't understand how to resolve my problem

like image 650
jmlncr Avatar asked Dec 05 '25 22:12

jmlncr


1 Answers

You're hooking the click handler on the server, but you're clicking the element on the client.

Instead, you need to send script code to the client that hooks up the event handler on the DOM element the browser renders, to handle the click and show the alert (which is also a client-side thing). (Which means you don't need JSDom; that's for doing DOM manipulation — like web scraping — server-side.)

like image 182
T.J. Crowder Avatar answered Dec 08 '25 11:12

T.J. Crowder