【问题标题】:Make userscript run when new contents on Facebook are loaded加载 Facebook 上的新内容时运行用户脚本
【发布时间】:2013-12-08 19:38:52
【问题描述】:
【问题讨论】:
标签:
javascript
facebook
userscripts
【解决方案1】:
这很难看,但是使用 window.setTimeout() 函数可以做到...当然是 p 代码。
var updateStuff() {
var els = document.GetElementsByClassNames("ThingsToLookFor");
for (var i = 0; i < els.length; i++) {
var el = els[i];
if (el["data-touched"]) {
// We've seen this
continue
}
// Update the element or whatever you do
el["data-touched"] = true;
window.setTimeout(updateStuff, 250);
}
}
// Kick it off
updateStuff();
实际上不要使用 data-touched -- 我不想寻找真正的语法来更新 data-* 东西,或者你可以使用 el.setAttribute("data-touched", true)
【解决方案2】:
最后我用MutationObserver:
// select the target node for mutation observation
var target = document.body;
// create an observer instance
var observer = new MutationObserver(function(mutations) { // mutations: an array of MutationRecord objects
mutations.forEach(function(mutation) {
var addedList = mutation.addedNodes;
for (var i = 0; i < addedList.length; ++i) {
// do something with addedList[i]
}
});
});
// configuration of the observer:
var config = { attributes: true, childList: true, characterData: true, subtree: true };
// pass in the target node, as well as the observer options
observer.observe(target, config);