Why don't my Greasemonkey scripts work in Chrome?
My Greasemonkey scripts all work in Firefox 3.6, but in Chrome 6 nothing special happens when I load a page that is supposed to trigger them. Here's an example script (pasted below) that highlights top comments on Hacker News. Can anyone identify what I'm doing wrong? When I click on the user.js file and install it in Chrome, the installation succeeds.
// ==UserScript==
// @name Hacker News highlight
// @namespace http://news.ycombinator.com
// @description highlights popular comments
// @include http://news.ycombinator.com/item*
// ==/UserScri开发者_运维百科pt==
var GM_JQ = document.createElement('script');
GM_JQ.src = 'http://jquery.com/src/jquery-latest.js';
GM_JQ.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(GM_JQ);
// Check if jQuery's loaded
function GM_wait() {
if(typeof unsafeWindow.jQuery == 'undefined') { window.setTimeout(GM_wait,100); }
else { $ = unsafeWindow.jQuery; letsJQuery(); }
}
GM_wait();
function letsJQuery() {
var maxScore = 0;
var secBest = 0;
var min = 0;
var numComments = 0;
$(".comhead > span").each(function() {
numComments = numComments + 1;
var score = parseInt($(this).text().split(' ')[0]);
if(score > maxScore) {
maxScore = score;
}
else if(score > secBest) {
secBest = score;
}
});
min = maxScore - secBest;
$(".comhead > span").each(function() {
var score = parseInt($(this).text().split(' ')[0]);
if(min!=0 && score >= min + 1) {
$(this).css({'background-color':'#B2D7FB', 'padding':'4px 4px 4px 4px','-moz-border-radius':'3px', '-webkit-border-radius':'3x'});
}
});
}
I have found it easiest to access page resources by injecting my code into the DOM:
// ==UserScript==
// @name Hacker News highlight
// @namespace http://news.ycombinator.com
// @description highlights popular comments
// @include http://news.ycombinator.com/item*
// @run-at document-end
// ==/UserScript==
function letsJQuery() {
// your stuff
}
var jQuery = document.createElement("script"),
inject = document.createElement("script");
jQuery.setAttribute("type", "text/javascript");
jQuery.setAttribute("src", "http://code.jquery.com/jquery-latest.js");
inject.setAttribute("type", "text/javascript");
inject.appendChild(document.createTextNode("(" + letsJQuery + ")()"));
document.body.appendChild(jQuery);
document.body.appendChild(inject);
The @run-at
ensures that the script loads immediately after DOMDocumentReady
, just as in Greasemonkey, and I changed your jQuery URL to point to their CDN.
I found the solution here. My scripts now work.
精彩评论