0

I'm trying to capture all images in an HTML page using Javascript. I found this similar question, the best answer to which gives in excellent detail a solution to the problem: Detect all images with Javascript in an html page

My question is that I can't get the code shown in the best answer to run without error - even when I copy/paste directly into the Firefox console. I suspect the answer is straightforward, though it's had me scratching my head for hours - is anyone able to help please?

This code gives me the error "SyntaxError: missing ) after argument list"...

var elements = document.body.getElementsByTagName("*");
Array.prototype.forEach.call( elements, function ( el ) {
    var style = window.getComputedStyle( el, false );
    if ( style.backgroundImage != "none" ) {
        images.push( style.backgroundImage.slice( 4, -1 ).replace(/['"]/g, "")
    }
}

The full solution, which seems to include the above, also appears to give the same error...

var images = [],
    bg_images = [],
    image_parents = [];
document.addEventListener('DOMContentLoaded', function () {
    var body = document.body;
    var elements = document.body.getElementsByTagName("*");

    /* When the DOM is ready find all the images and background images
        initially loaded */
    Array.prototype.forEach.call( elements, function ( el ) {
        var style = window.getComputedStyle( el, false );
        if ( el.tagName === "IMG" ) {
            images.push( el.src ); // save image src
            image_parents.push( el.parentNode ); // save image parent

        } else if ( style.backgroundImage != "none" ) {
            bg_images.push( style.backgroundImage.slice( 4, -1 ).replace(/['"]/g, "") // save background image url
        }
    }

    /* MutationObserver callback to add images when the body changes */
    var callback = function( mutationsList, observer ){
        for( var mutation of mutationsList ) {
            if ( mutation.type == 'childList' ) {
                Array.prototype.forEach.call( mutation.target.children, function ( child ) {
                    var style = child.currentStyle || window.getComputedStyle(child, false);
                    if ( child.tagName === "IMG" ) {
                        images.push( child.src ); // save image src
                        image_parents.push( child.parentNode ); // save image parent
                    } else if ( style.backgroundImage != "none" ) {
                        bg_images.push( style.backgroundImage.slice( 4, -1 ).replace(/['"]/g, "") // save background image url
                    }
                } );
            }
        }
    }
    var observer = new MutationObserver( callback );
    var config = { characterData: true,
                attributes: false,
                childList: true,
                subtree: true };

    observer.observe( body, config );
});

Thank you.

  • Many brackets are misaligned and unclosed, eg the `(` in `images.push(`. The answer you're copying the bad code from from is not very good – CertainPerformance Sep 22 '19 at 22:05
  • 1
    Thanks for your frank feedback, @CertainPerformance! Is it the syntax errors alone that led you to say the code is bad, or are there aspects of its general functionality that you think could be improved? – FishOnABicycle Oct 01 '19 at 22:31
  • If the code works once the syntax errors are fixed, that's good enough, I guess, though there are a *lot* of things to improve on, just in the context of general code quality. (eg, better to use modern syntax, abstract the two identical `forEach` blocks into a single function, `continue` instead of a large `if` block, declare variables only in the context of where they're going to be used, etc.) Concise, refactored, modern code results in less surface area for bugs and typos – CertainPerformance Oct 02 '19 at 01:53

1 Answers1

1

You're missing some closing parentheses on the images.push() line and the last line.

Not sure if this will make your code do what you ultimately want it to do, but it will at least not cause a syntax error.

var elements = document.body.getElementsByTagName("*");
Array.prototype.forEach.call( elements, function ( el ) {
    var style = window.getComputedStyle( el, false );
    if ( style.backgroundImage != "none" ) {
        images.push(style.backgroundImage.slice(4, -1).replace(/['"]/g, ""));
    }
});
Nick Tiberi
  • 1,132
  • 12
  • 20
  • 1
    Thanks, Nick - that was very helpful. Based on your response, I've been rereading the code and notice a number of issues. I've corrected some now, though realise the second half (starting with comment "MutationObserver callback to add images when the body changes" is going to need some serious unpicking. Some of it still even looks like pseudo code. If you have any pointers, I'd be most grateful. Thanks. – FishOnABicycle Oct 01 '19 at 23:07