Greasemonkey脚本不会附加到id

时间:2014-08-08 03:36:13

标签: jquery append greasemonkey

我正在尝试编写我的第一个Greasemonkey脚本,而且我不确定它为什么不起作用。警报会显示它们应该显示的内容,但.append不起作用。我现在在非本地站点上运行本地计算机上的脚本。

为什么它不起作用?

// ==UserScript==
// @name        LootTracker
// @namespace   Kong
// @include     http://www.kongregate.com/games/5thPlanetGames/*
// @version     1
// @grant       none
// @require     http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js
// ==/UserScript==

alert('1');
LootTabHeaderText = "<li id='loot_tab'></li>";
alert(LootTabHeaderText);
$("#main_tab_set").append(LootTabHeaderText); //doesn't fire

2 个答案:

答案 0 :(得分:2)

您的目标站点已经使用了jQuery,并且您的脚本正在其上加载不同的jQuery。 Loading jQuery in @grant none mode busts the page, or the script, or both

另外:

  1. 标识为main_tab_set的节点并不总是存在,可能是通过AJAX添加的。你需要AJAX技术。

  2. 该节点可能位于iFrame中。您需要为此调整脚本的@include语句。

  3. (请注意,在60秒的时间里,我根本没有看到那个节点。)

    所以,将脚本更改为:

    // ==UserScript==
    // @name        LootTracker
    // @namespace   Kong
    // @include     http://www.kongregate.com/games/5thPlanetGames/*
    // @version     1
    // @require     http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
    // @require     https://gist.github.com/raw/2625891/waitForKeyElements.js
    // @grant       GM_addStyle
    // ==/UserScript==
    /*- The @grant directive is needed to work around a design change
        introduced in GM 1.0.   It restores the sandbox.
    */
    console.log ('1');
    LootTabHeaderText = "<li id='loot_tab'>Loot tab</li>";
    console.log (LootTabHeaderText);
    
    waitForKeyElements ("#main_tab_set", appendListItem);
    
    function appendListItem (jNode) {
        jNode.append (LootTabHeaderText); 
        console.log ("Node found!");
    }
    


    除非内容位于iframe中,否则这将有效。在这种情况下,请调整@include以在iframe上触发。

    打开控制台( Ctrl Shift K )以查看调试消息。

答案 1 :(得分:0)

你错了。你的事件会触发,但元素不存在。这是一个有效的代码。

// ==UserScript==
// @name        LootTracker
// @namespace   Kong
// @include     http://www.kongregate.com/games/5thPlanetGames/*
// @version     1
// @grant       none
// @require     http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js
// ==/UserScript==

// Page elements must load first
// On page load run this code
$(function(){
  checkDOMChange();
});

var times = 0;
function checkDOMChange()
{
  // If there is no menu
  if( $("#main_tab_set").length==0 ){
    times++;
    if(times<=100) // Give 10secs max
     setTimeout( checkDOMChange, 100 );

  }else{

    // Now Lets make the menu tab
    LootTabHeaderText = '<li class="tab" id="loot_tab"><a href="#loot_tab_pane" class="">Loot</a></li>';
    $("#main_tab_set").append(LootTabHeaderText);

  }
}

快乐编码