浏览器加载新的内联(ajax)内容时触发的Javascript事件?

时间:2018-05-31 13:04:21

标签: javascript html ajax events javascript-events

是否有浏览器加载新的内联(ajax)内容时触发的javascript事件?我想在我的浏览器扩展程序中捕获新内容。感谢所有

window.onload = function() {
    var observer = new MutationObserver(function(mutations) {
        alert("hello");
    });

    var config = {
        attributes: true,
        childList: true,
        characterData: true
    };

    observer.observe($('#contentArea'), config);
}

1 个答案:

答案 0 :(得分:0)

使用 DOM Mutation Observer 很可能就是您想要的。

// Since you are using JQuery, use the document.ready event handler
// which fires as soon as the DOM is fully parsed, which is before
// the load event fires.
$(function() {
    var observer = new MutationObserver(function(mutations) {
        alert("DOM has been mutated!");
    });

    var config = {
        attributes: true,
        childList: true,
        characterData: true
    };

    // You must pass a DOM node to observe, not a JQuery object
    // So here, I'm adding [0] to extract the first Node from 
    // the JQuery wrapped set of nodes.
    observer.observe($('#contentArea')[0], config);
    
    // Then, the DOM has to be mutated in some way:
    $("#contentArea").html("<p>test</p>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="contentArea"></div>