Greasemonkey脚本用于处理Facebook上动态加载的帖子

Ddw*_*dsf 2 javascript greasemonkey facebook

我写了一个Greasemonkey脚本,它会影响Facebook上首次加载的帖子.但是在向下滚动源后,脚本不适用于新加载的帖子.

有没有办法重新运行这些帖子的脚本,或类似的东西?谁能帮我?

Bro*_*ams 8

更新:
此问题和答案非常陈旧,DOMSubtreeModified已弃用.
我不再推荐这种方法.相反看:



老答案:

是的,因为您使用的是Firefox,所以可以触发DOMSubtreeModified事件.

为此,首先将当前脚本的代码部分包装在函数中; 例如:

// ==UserScript==
// @name            Facebook Fixer
// ==/UserScript==

function LocalMain ()
{
    //--- Do all of your actions here.
}

LocalMain (); //-- Fire GM script once, normally.
Run Code Online (Sandbox Code Playgroud)

接下来,找到包含新加载的帖子的节点.假设您发现它是一个divID为"All_posts_go_here"(我不使用Facebook,请务必找到正确的节点,并且不要使用body,浏览器会慢慢爬行).

一旦确定了正确的节点,就可以设置事件监听器.但是,您还需要一个短暂的时间延迟,因为节点一次变化数百个,您需要等到当前批次完成.

所以,把它们放在一起,代码看起来像这样:

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

function LocalMain ()
{
    //--- Do all of your actions here.
}

LocalMain (); //-- Fire GM script once, normally.


var PostsChangedByAJAX_Timer    = '';
//--- Change this next line to find the correct element; sample shown.
var PostContainerNode           = document.getElementById ('All_posts_go_here');

PostContainerNode.addEventListener ("DOMSubtreeModified", PageBitHasLoaded, false);


function PageBitHasLoaded (zEvent)
{
    /*--- Set and reset a timer so that we run our code (LocalMain() ) only
        AFTER the last post -- in a batch -- is added.  Adjust the time if needed, but
        half a second is a good all-round value.
    */
    if (typeof PostsChangedByAJAX_Timer == "number")
    {
        clearTimeout (PostsChangedByAJAX_Timer);
        PostsChangedByAJAX_Timer  = '';
    }
    PostsChangedByAJAX_Timer      = setTimeout (function() {LocalMain (); }, 555);
}
Run Code Online (Sandbox Code Playgroud)

请注意,我假设节点不是iframe.如果是,则可能需要不同的方法.