2017-04-14 120 views
0

加载younow网站时,消息框“开始”弹出两次。 -我怎样才能解决这个问题?Younow onLoad(with greasemonkey)

// ==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"); 
}); 

回答

1

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'); 
}