How do I return a value from a simple jsdom function?

不想你离开。 提交于 2019-12-03 15:41:21

I don't think you can do this using a return value, because done: is an async function. Try adding a callback to your tweakIt and get the new html by sending it as a parameter, e.g.

tweakIt(oldHtml, function(newHtml) {/*use the result here*/})

The new version of the JSDOM API no longer includes the 'done' callback option.

So I wrote a 'poor man's callback' to access a DOM variable only after it has been set.

function getSomeDOMVar(callback) {

    const jsdom = require("jsdom");
    const { JSDOM } = jsdom;

    const dom = new JSDOM(`
    <!DOCTYPE html>
    <html>
        <body>
            <script>
                var result; // globally scoped, undefined var, accessible in the node scope as dom.window.result

                function doSomething() {
                    // your code goes here
                }

                // then assign the data you want back to your the globally scoped var
                result = doSomething();

            </script>
        </body>
    </html>
    `, {
        runScripts: "dangerously",
        resources: "usable"
    });

    // poor man's callback
    function waitForVar() {
        if (typeof dom.window.result !== 'undefined') {
           cb(dom.window.result);
        }
    }
    setTimeout(waitForVar, 1000);
}

getSomeDOMVar(function(result) {
    console.log(result)
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!