2017-04-14 117 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'); 
}