0

所以我有这个脚本:

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

在我要修改的页面加载后在暂存器中工作。

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

这是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.
4

1 回答 1

1

您的脚本必须等待页面的 javascript 加载这些缩略图。最简单、最可靠的方法是使用waitForKeyElements() 实用程序

这是一个使用jQuery并更改这些s的完整脚本:waitForKeyElementshref

// ==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);
}
于 2013-03-26T04:34:03.570 回答