Client-Side ajaxComplete Call Generating Infinite

2019-07-20 20:11发布

问题:

Alright, so here is my issue. I'm writing a Greasemonkey script to insert two iframes on an AJAXified site, but ajaxComplete gets caught in a loop and generates an excess number of iframes (sometimes one, sometimes five, etc...), gener.

I've done my research and [I think] my problem is that I'm not binding the call to the document properly, but of this I am unsure. I'm not sure how you would do it differently than I already have. If you guys could point me in the right direction I'd be grateful. Here is the offending code:

function OnLoadWidgets() {
    var tempSC = document.createElement("div");                                        
        tempSC.id = "SCWidget";
        tempSC.innerHTML = "..."
    document.getElementById("content-right").appendChild(tempSC);
    var tempMC = document.createElement("div");                                        
        tempMC.id = "MCWidget";
        tempMC.innerHTML = "..."
   document.getElementById("content-right").appendChild(tempMC);

}   

unsafeWindow.jQuery(document).ajaxComplete(function()
{   
    var existingSCPlayer = document.getElementById("SCWidget");                     
    if(typeof(existingPlayer) == "undefined")
    {
        OnLoadWidgets();
    }
});

You can see the rest of the code here: http://userscripts.org/scripts/show/127312

Also wanted to use this a chance to thank you guys for all your hard work. Can't thank you enough, really. stack == lifesaver

回答1:

(1) The target site, hypem.com, uses its own iframes and your Greasemonkey script will fire on those also.

Prevent this by adding:

if (window.top != window.self)  //-- Don't run on frames or iframes.
    return;

near the top of the script.


(2) There is a variable name typo in the code. existingSCPlayer versus existingPlayer.


(3) Refine the duplicate check to be a little more inclusive. Use this code:

unsafeWindow.jQuery (document).ajaxComplete ( function () {
    var existingSCPlayer = document.getElementById ("SCWidget");
    var existingMCPlayer = document.getElementById ("MCWidget");
    if ( ! existingSCPlayer  &&  ! existingMCPlayer) {
        OnLoadWidgets();
    }
} );