脚本在firefox暂存器中工作,但不在greasemonkey中

时间:2013-03-26 02:23:19

标签: javascript greasemonkey document-ready

所以我有这个脚本:

links = document.getElementsByClassName('thumb');
for (var i=links.length-1; i>=0; i--)
{
links[i].href=links[i].href+'/popout';
}

在页面上,我想要修改后,在暂存器中工作。

但是当我把它放在greasemonkey中时,它会在页面完全加载之前运行,而我需要mod的元素不存在而且它不起作用。

这是gs脚本:

// ==UserScript==
// @name        popout
// @namespace   PylonPants
// @include     http://*.twitch.tv/directory/*
// @version     1

// ==/UserScript==

//if ('loading' == document.readyState) {
//  alert("This script is running at document-start time.");
//} else {
//  alert("This script is running with document.readyState: " + document.readyState);
//}
// script runs at readyState = interactive and that brakes it
// do not know how to make it wait till complete

links = document.getElementsByClassName('thumb');
alert(links[0]); // i get "undefined"
for (var i=links.length-1; i>=0; i--)
{
alert('the script works'); //i never reach here
alert(links[i].href); // nor here
links[i].href=links[i].href+'/popout';
}
alert('crazy'); // i get this then the page loads fully.

1 个答案:

答案 0 :(得分:1)

您的脚本必须等待页面的javascript加载这些缩略图。最简单,最强大的方法是使用the waitForKeyElements() utility

这是 完整脚本 ,它使用jQuerywaitForKeyElements来更改href

// ==UserScript==
// @name        popout
// @namespace   PylonPants
// @include     http://*.twitch.tv/directory/*
// @require     http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/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.
*/

waitForKeyElements ("a.thumb", adjustLinkHrefs);

function adjustLinkHrefs (jNode) {
    var newAddr = jNode.attr ("href") + '/popout';
    jNode.attr ("href", newAddr);
}