首页 > 解决方案 > 使用javascript从数组中的HTML页面捕获图像

问题描述

我正在尝试使用 Javascript 捕获 HTML 页面中的所有图像。我发现了这个类似的问题,最好的答案非常详细地给出了该问题的解决方案: Detect all images with Javascript in an html page

我的问题是,即使我直接复制/粘贴到 Firefox 控制台中,我也无法获得最佳答案中显示的代码以正常运行。我怀疑答案是直截了当的,虽然它让我挠了好几个小时——有人能帮忙吗?

这段代码给了我错误“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, "")
    }
}

似乎包括上述内容的完整解决方案似乎也给出了相同的错误......

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 );
});

谢谢你。

标签: javascripthtmlcssimage

解决方案


您在该images.push()行和最后一行缺少一些右括号。

不确定这是否会使您的代码执行您最终希望它执行的操作,但至少不会导致语法错误。

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, ""));
    }
});

推荐阅读