![](https://img-blog.csdn.net/20181017154827989?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3h1dG9uZ2Jhbw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70)
<!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>