How do you add stylesheets to JSDOM

前端 未结 1 1659
日久生厌
日久生厌 2021-01-02 03:06

I am currently working on a project that requires me to have computed styles send to the browser via JSDOM. I am currently looking for a way to inject some basic CSS into JS

1条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-02 03:44

    Well, this is going to sounds kinda dumb but this is what I did:

        var path = require('path');
        var fs = require('fs');
        var mainCss = fs.readFileSync(path.normalize(__dirname + "web_main.css"), 'utf8');
        var document = jsdom.jsdom('', jsdom.level(3, 'index'), {
            features : {
                FetchExternalResources : ['script', 'css'],
                QuerySelector : true
            }
        });     
        var window = document.createWindow();
        var head = document.getElementsByTagName('head')[0];
        style = document.createElement("style");
        style.type = 'text/css';
        style.innerHTML = mainCss;
        head.appendChild(style);
    

    So basically all I changed was moving the level to 3 index, and instead of directly having it in the starting html, I appended it afterwards.

    Its pretty simple and I hope it helps someone else out.

    0 讨论(0)
提交回复
热议问题