我的Greasemonkey脚本都可以在Firefox 3.6中运行,但在Chrome 6中,当我加载一个应该触发它们的页面时,没有什么特别的事情发生。 Here是一个示例脚本(粘贴在下面),突出了有关黑客新闻的热门评论。任何人都能确定我做错了什么吗?当我点击user.js文件并将其安装在Chrome中时,安装成功。
// ==UserScript==
// @name Hacker News highlight
// @namespace http://news.ycombinator.com
// @description highlights popular comments
// @include http://news.ycombinator.com/item*
// ==/UserScript==
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'});
}
});
}
答案 0 :(得分:0)
我找到了解决方案here。我的脚本现在有效。
答案 1 :(得分:0)
我发现通过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);
@run-at
确保脚本在DOMDocumentReady
之后立即加载,就像在Greasemonkey中一样,我将jQuery URL更改为指向他们的CDN。