Converting a javascript bookmark for use with greasemonkey?
I'm trying to get the following bookmark to act as a Greasemonkey script to work around an accessibility bug with the stackexchange sites.
javascript:(function(){$('a,%20.vote-up-off,%20.vote-down-off,%20.star-off').attr({role:'link',tabindex:'0'});})()
When I remove the function() and put it in the following Greasemonkey script it does not work.
// ==UserScript==
// @name StackExchange access
// @description Enables y-aria stuff on stackoverflow
// @include *
// ==/UserScript==
$('a,%20.vote-up-off,%20.vote-down-off,%20.star-off').attr({role:'link',tabindex:'0'});
alert("worldzz");
I'm guessing that I need to access the document object somehow from Greasemonkey but am not sure how to do this.
I know the scri开发者_StackOverflow社区pt is getting called because if I comment out the $('a,%20.vote-up-off,%20.vote-down-off,%20.star-off').attr({role:'link',tabindex:'0'})
line my alert gets hit.
- A greasemonkey script will not have access to jQuery directly. Greasemonkey sandboxes the script into its own scope so anything you need to access in the page's global scope (like jQuery) has to be accessed via
window.wrappedJSObject
- You need to replace all
%20
in your Greasemonkey version with a space char - You need to put the jQuery DOM manipulation in the ready function so that it doesn't run until the elements are on screen.
Code:
// ==UserScript==
// @name StackExchange access
// @description Enables y-aria stuff on stackoverflow
// @include *
// ==/UserScript==
( function( global )
{
var $;
if( global.jQuery )
{
$ = global.jQuery;
$( function()
{
$( 'a, .vote-up-off, .vote-down-off, .star-off' )
.attr( {
role:'link',
tabindex:'0'
} );
} );
}
}( window.wrappedJSObject ) );
Because a Greasemonkey script does not URL decode its source, you need to replace all
%20
with the space character.Then, to access the page's jQuery, if the page even has it, just use:
// ==UserScript== // @name StackExchange access // @description Enables y-aria stuff on stackoverflow // @include * // ==/UserScript== unsafeWindow.$ ('a, .vote-up-off, .vote-down-off, .star-off').attr({role:'link', tabindex:'0'}); alert("worldzz");
1. Note: Both this method, and especially JAAulde's answer, carry a slight risk that the web page can pwn your system.
An alternate method, (1) without the security risk, and that (2) works on pages that don't use jQuery; is for the GM script to use it's own jQuery.
Do that like so:
// ==UserScript==
// @name StackExchange access
// @description Enables y-aria stuff on stackoverflow
// @include *
// @require http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js
// ==/UserScript==
$ ('a, .vote-up-off, .vote-down-off, .star-off').attr({role:'link', tabindex:'0'});
alert("worldzz");
精彩评论