How can I adapt a JavaScript bookmark to work with Greasemonkey?

Trying to utilize the following bookmark as a Greasemonkey script to address an accessibility issue with stackexchange sites.

javascript:(function(){$('a,%20.vote-up-off,%20.vote-down-off,%20.star-off').attr({role:'link',tabindex:'0'});})()

However, when attempting to integrate it into the Greasemonkey script without the function(), it fails to 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");

The assumption is that there may be a need to somehow access the document object from within Greasemonkey, although the method for doing this remains unclear.

Confirmation of the script being executed is evident if the

$('a,%20.vote-up-off,%20.vote-down-off,%20.star-off').attr({role:'link',tabindex:'0'})
line is commented out and the alert triggers.

Answer №1

  1. When working with a Greasemonkey script, accessing jQuery directly is not possible since the script is sandboxed into its own scope. To access elements in the page's global scope, such as jQuery, you must use window.wrappedJSObject
  2. In your Greasemonkey version, remember to replace all instances of %20 with a space character
  3. To ensure that your jQuery DOM manipulation code executes only when the elements are visible on screen, it should be placed within the ready function.

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 ) ); 

Answer №2

  1. To correctly decode the source of a Greasemonkey script, it is necessary to replace all instances of %20 with the space character.

  2. If accessing the page's jQuery is required, the following code can be used:

    // ==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. Important: It should be noted that both this approach and JAAulde's answer carry a slight risk of compromising your system.



An alternative technique, (1) without the security concerns and that (2) functions on pages lacking jQuery; involves the GM script using its own jQuery library.

Here is how it can be done:

// ==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");

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Event Listener for Spelling Quiz Buttons: Check Correct and Incorrect Answers

I am currently in the process of developing a spelling quiz for a project website using HTML, CSS, and JavaScript. The idea is to present the user with a word that has two missing letters indicated by underscores. The user then selects the correct answer ...

Utilize React and Jest to handle errors by either mocking window values or resolving them

When my app attempts to inject environmental variables at runtime for docker using the window object, I encounter errors in my tests. The code snippet below shows the configuration: url config: declare const window: Window & typeof globalThis & ...

Exploring the relationship between $resource and controllers

I am currently working on deciphering the code snippets below. From what I gather, there are three resource objects - CategorySrv, ArticleSrv, and SearchSrv that interact with REST server data sources. app.factory('CategoryService', function($re ...

Creating a box that is connected by lines using JSON data requires several steps. You

I am attempting to dynamically draw a line using the provided JSON data. I have heard that this can be easily achieved with flexbox. Important: I would greatly appreciate a solution involving flexbox This is what I hope to achieve: https://i.stack.imgu ...

Ajax response values overlap

I am developing an application that requires multiple Ajax requests, but I encountered a problem where I am receiving the same response values for both requests. Each request must include a data field called activityCode, yet I keep getting the value of Sc ...

Is it possible to create Interactive Tabs using a Global BehaviorSubject?

Trying to adjust tab visibility based on different sections of the Ionic app, an approach involving a global boolean BehaviorSubject is being utilized. The encapsulated code has been condensed for brevity. In the provider/service globals.ts file, the foll ...

Which is more effective: coding with just plain JavaScript and CSS, or utilizing frameworks?

As a student, is it more beneficial to focus on utilizing pure JavaScript & CSS or frameworks? And which approach is best suited for the professional field? ...

Can an arrow be crafted to direct a player towards their final destination?

I'm currently developing a game that utilizes numerical tile maps, such as [1, 0, 0, 1], and I am using JavaScript to display these maps on a canvas. I have been struggling to create an arrow that consistently rotates to point towards an end goal, des ...

Tips for concealing the boundary lines within a Polararea chart utilizing vue-chartjs

I am currently working on a project that involves a polararea chart using vue-chartjs and I am facing an issue with hiding the 'area lines' (the circle ones) and the percentage numbers on them in this chart. Unfortunately, I couldn't find an ...

disabling a submit button

I am new to coding and need help disabling a button on document load. Can someone assist me with this? Here is my current code snippet: $(document).ready(function() { setTimeout("check_user()", 250); }); Your guidance is greatly appreciated! ...

Looking for a rival on socket.io

Currently, I am working on a script utilizing socket.io with express in node.js to find an opponent. In this setup, only two players are allowed in a room. If no free rooms are available, a new one should be created automatically. The core logic of the c ...

Running PHP scripts one after the other with ajax requests

This situation has been puzzling me for quite some time now. I have an ajax call set up like this: function update() { $.get("update.php", function(data) { $("#output-progress").html(data); }); } And I trigger it like this: window.se ...

How to accurately determine the width of an element using JavaScript

Consider this scenario where I have created a custom dropdown list using HTML within a generic div: $(document).ready(function() { $("#selectbox-body").css("width", $("#selectbox").width()); }); <script src="https://ajax.googleapis.com/ajax/libs/ ...

Understanding the getJSON MethodExplaining how

$.getJSON( main_url + "tasks/", { "task":8, "last":lastMsgID } I'm a bit confused about how this code functions. I'm looking for a way to retrieve messages from a shoutbox using a URL or some sort of method that the function here ...

error fetching data: unable to access due to client blocking

Despite including all possible information in my request, I am still encountering the same error. How can I identify the root cause of this issue? I have already disabled my AdBlocker extension. await fetch('http://127.0.0.1:8080/hxo.json?dummy=2s21&a ...

What is the method to determine the size of an array of objects where each object contains its own internal array?

Here is the data that I have: var a=[ { name: "time", Details:[ {value:"month",checked:true,id:1} ] }, { name: "product", Details:[ {value: ...

What is the best way to extract a particular key value from a JSON object?

I am completely new to the world of APIs and just starting out with JavaScript. My goal is to retrieve the status of a server from a server hosting panel using an API. In order to achieve this, I need to log in by making a request to /API/Core/Login, extra ...

Delete items from several arrays on a click event in React

I'm working with an array of objects that contain multiple arrays. My goal is to remove the item when a button is clicked, but I keep getting undefined as a result. JSON Data [ { "services": [ { "id": "1b9 ...

What steps should I follow to generate a table using Ajax and Javascript when a button is clicked?

After spending hours following various tutorials and exploring previously asked questions, I am struggling to make this work. My HTML page looks like this: <!DOCTYPE html> <html> <head> <link type="text/css" rel="styleshee ...

When working with ES6 modules, the value of `this` and $(this) can be undefined

I attempted to integrate the toggleImage functionality into a gallery and referenced this thread along with the code provided in one of the responses. However, upon doing so, I encountered the error message Uncaught TypeError: Cannot read property 'at ...