Younow onLoad(使用 greasemonkey)

Younow onLoad (with greasemonkey)

加载 younow 网站时,消息框 "Start" 弹出两次。 -我该如何解决这个问题?

// ==UserScript==
// @name        test
// @include   https://www.younow.com/*
// @version     1
// @grant       none
// @require http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js
// ==/UserScript==
$(document).ready(function() { 
alert("Start");
});

alert 在这个网站上是这样的,可能是因为调用后重新加载,但是有一个前缀对我来说没问题。

$(document).ready(function() { 
  $('body').prepend("toto"); // your code here
});

另外你不需要使用 ready 函数,greasmonkey 会在正确的时间启动你的脚本。

但问题是:

  1. 我想您想在加载所有 ajax 元素后做您的事情。所以最好的方法是观察 dom.
  2. 由于网站使用 AJAX 单击请求更改当前页面并且 hashchange 事件不起作用,我使用一些技巧来监听任何页面更改。

通过此脚本,您可以使用 alert 函数:

// ==UserScript==
// @name        test
// @include   https://www.younow.com/*
// @version     1
// @grant       none
// @require https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js
// ==/UserScript==

var observer = null;
initObserver();

function initObserver()
{
  observer = new MutationObserver(onMutation);
  observer.observe(document,
  {
    childList: true, // report added/removed nodes
    subtree: true,   // observe any descendant elements
  });
}

$(window).on('hashchange', function(e)
{
     initObserver();
});

intervalMutation = setInterval(onMutation.bind(null, null), 1000);

function locationObserver()
{
  var oldLocation = location.href;
   setInterval(function() {
        if(location.href != oldLocation) {
             onMutation(null);
             oldLocation = location.href
        }
    }, 1000); // check every second
}
locationObserver();

function onMutation(mutations)
{
  // Check if this class exits:
  if($('.trending-now').length ||
     $('.ynicon ynicon-chat').length ||
     $('.trending_title').length ||
     $('.trending-tags-list').length)
  {
     // Disconnect the observer:
     observer.disconnect();
     // Clear the interval :
     clearInterval(intervalMutation);
     // Call your code:
     pageReady();
  }
}

function pageReady()
{
  // your code here:
  alert('start');
}