Ad

How To Find Specific JavaScript Code In Parsed HTML Using Cheerio With Nodejs?

- 1 answer

I want to find a single JavaScript code/keyword like zopim or v2.zopim.com in whole script with using cheerio on NodeJS. I wrote a script that grabs all links from a single web site but the script need to opens all these grabbed links and search for "zopim" keyword in JavaScript codes. I looked cheerio's repository and it's issues but no luck. I'm wondering could anyone help me to figure out this situation? This is a part of my code that where I open links and search in source code for a keyword. I can post all of it if it's necessary.

function () {
    //console.log(totalUrls);
    console.log("Crawling is done.")
    if (page == 16) {
        console.log("Anaylzing web sites...");
        async.whilst(
            function () {
                return checkedUrl < totalUrls.length;
            },
            function (urlCallback) {
                var currentUrl = totalUrls[checkedUrl]
                request(currentUrl, function (err, res, body) {
                    if (err) {
                        console.log('Error: ' + err);
                    }
                    var $ = cheerio.load(body);
                    $('.headerContent').each(function () {
                        var title = $(this).find('a').text();
                        console.log(currentUrl + title);// if the current web site has a '.headerContent' class print it.
                        // I want to print only if web site source code includes "zopim" keyword in JavaScript code
                    });
                    checkedUrl++;
                    urlCallback();
                });
            }
        );
    }
}
Ad

Answer

You can use :contains selector to find scripts which contain keyword 'zopim' in text and then count found script elements:

const scriptsWithKeywordCount = $('script:contains("zopim")').length;
if (scriptsWithKeywordCount > 0) {
    // webpage contains keyword in javascript code
}
Ad
source: stackoverflow.com
Ad