I'm writing a webscraping script and I'd like to use getComputedStyle()
however it doesn't work on node. I get errors saying getComputedStyle is not defined
If I try global.getComputedStyle
, it says global.getComputedStyle is not a function
Obviously window doesn't exist on node so I can't use that.
What do I need to use?
function sortElementsByFontSize(elements: any[]): any[]{
return elements.sort((a, b) => {
let aFontSize = parseInt(global.getComputedStyle(a)['fontSize']);
let bFontSize = parseInt(global.getComputedStyle(b)['fontSize']);
console.log("Comparing: " + aFontSize + " - " + bFontSize);
if(aFontSize === bFontSize){
return 0;
} else {
return aFontSize > bFontSize ? 1 : -1
}
});
}
getComputedStyle()
is something that exists in a browser, not in nodejs.
If this wasn't clear to you, nodejs is a Javascript environment and it supports the latest standards for the Javascript language, but it has its own runtime library that supports things like networking and file I/O. Similarly, the browser supports the latest standards for the Javascript language, but has its own runtime library that supports things like getComputedStyle()
.
Nodejs doesn't do any HTML rendering on its own, doesn't parse or understand CSS, etc...
So, to use a function like getComputedStyle()
you have to either run your Javascript in a browser environment or use a library within nodejs that gives you access to an actual browser engine such as Puppeteer which uses the Chromium browser engine to create a browser-environment where you can run some Javascript.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With