How to implement jQuery within a Greasemonkey userscript for Gmail modifications

I want to create a userscript that modifies Gmail’s interface colors using jQuery for element selection. I keep running into problems with the setup and debugging process.

The main issues I’m facing:

  • Fixed the @require directive but now struggling to find the right elements in Gmail’s complex DOM structure
  • Most divs only have the .nH class which makes targeting specific elements difficult
  • My target is the blue header bar that appears above the email list
  • GM_log statements don’t seem to work
  • Getting “jQuery is not defined” errors

I think the jQuery library might be getting unloaded after my script runs. Is there a way to keep jQuery available throughout the script execution? Also, any tips for testing selectors directly in the browser console would be helpful.

Gmail loads everything async, so timing matters big time. I use window.addEventListener('load', function() { ... }) with a small delay to make sure everything’s rendered before jQuery grabs it. For the .nH class problem - Gmail’s classes are pretty generic, but you can get more specific with descendant selectors. The blue header’s tricky, but try targeting div[jscontroller] attributes or aria-label properties since they don’t change as much as CSS classes. What really helped me was adding // @run-at document-end to the userscript metadata. It runs after the DOM builds but before everything finishes loading - that’s the sweet spot for Gmail mods.

try wrapping ur script in (function() { ... })(); to avoid conflicts. gmail’s dom is pretty messy; check devtools to inspect elements and test selectors right in console. also, use console.log() for debugging instead of GM_log, way more reliable.

The jQuery loading issue happens because Gmail’s dynamic content overwrites the global scope. I fixed this by adding @grant none to my userscript header - this runs the script in the page context instead of a sandbox, so jQuery stays accessible.

For targeting Gmail elements, use attribute selectors instead of classes since Gmail changes CSS classes all the time. The blue header bar usually has role="banner" or sits under elements with data- attributes. Try document.querySelector('[role="banner"]') or similar.

For debugging, test your jQuery selectors in the browser console first before putting them in your script. Also make sure your script runs after DOM loads by checking document.readyState or using a mutation observer to wait for elements to show up.