MutationObserver 监听页面的DOM元素是否发生了变化 (调试网页劫持)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xutongbao/article/details/83111158

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>MutationObserver 监听页面的DOM元素是否发生了变化 (调试网页劫持)</title>
    <style>
    body {
        margin: 0;
        padding: 0;
    }
    </style>
    <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js"></script>
</head>

<body>
    <button id="btn1" onclick="createE()">create element</button>
    <button id="btn2" onclick="changeA()">change attr</button>
    <div id="container">
        <form id="form1" action="/">
        </form>
    </div>
    <script>
    btn1.onclick = function() {
        var container = document.getElementById('container');
        var eA = document.createElement('a');
        eA.innerHTML = '百度'
        eA.href = "http://www.baidu.com";
        container.appendChild(eA);
    };

    btn2.onclick = function() {
        form1.action = "http://www.qq.com";
    };

    var observer = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
            if (mutation.type === 'childList') {
                // 在创建新的 element 时调用
                console.log("child list: ");
                console.log(mutation);
            } else if (mutation.type === 'attributes') {
                // 在属性发生变化时调用
                console.log("attributes: ");
                console.log(mutation);
            }
        });
    });

    observer.observe(window.document, {
        subtree: true,
        childList: true,
        attributes: true,
        attributeFilter: ['src', 'href', 'action']
    });
    </script>
</body>

</html>

猜你喜欢

转载自blog.csdn.net/xutongbao/article/details/83111158