【问题标题】:Make userscript run when new contents on Facebook are loaded加载 Facebook 上的新内容时运行用户脚本
【发布时间】:2013-12-08 19:38:52
【问题描述】:

我正在编写一个用户脚本,用另一个单词替换页面中出现的每个单词(想想the cloud -> my butt)。它基于这个脚本https://github.com/panicsteve/cloud-to-butt/blob/master/Source/content_script.js

通常这很容易。我只需要在页面加载完成时运行它。但是,我正在对 Facebook 新闻提要执行此操作,并且该脚本仅适用于最初加载的内容。当我向下滚动并加载新内容时,脚本不会触及这些新内容中的文本。

我怎样才能使当我向下滚动页面时加载新内容时,脚本再次运行?

【问题讨论】:

    标签: 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);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-05-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-09-03
        • 1970-01-01
        • 1970-01-01
        • 2013-01-19
        相关资源
        最近更新 更多