我写了一个 Greasemonkey 脚本,它影响了 Facebook 上最先加载的帖子。 但是在您向下滚动提要后,该脚本对新加载的帖子不起作用。
有没有办法为这些帖子重新运行脚本,或者类似的东西?谁能帮帮我?
最佳答案
更新:
这个问答很老了DOMSubtreeModified
is deprecated .
我不再推荐这种方法。请参阅:
- Fire Greasemonkey script on AJAX request
- Run Greasemonkey script on the same page, multiple times?
- Choosing and activating the right controls on an AJAX-driven site
- 或者通过类似Mutation Summary 的库使用
MutationObserver
,或类似的。
旧答案:
是的,因为您使用的是 Firefox,您可以触发 DOMSubtreeModified
事件。
为此,首先将当前脚本的代码部分包装在一个函数中;例如:
// ==UserScript==
// @name Facebook Fixer
// ==/UserScript==
function LocalMain ()
{
//--- Do all of your actions here.
}
LocalMain (); //-- Fire GM script once, normally.
接下来,找到包含新加载的帖子的节点。假设你发现它是一个id为"All_posts_go_here"的div
(我不使用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);
}
请注意,我假设节点不是 iframe。如果是,则可能需要采用不同的方法。
关于javascript - Greasemonkey 脚本,用于处理 Facebook 上动态加载的帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5890110/