0

I'm trying to create a simple Greasemonkey script using jQuery. jQuery is already loaded from the page script.

I need a very simple change:

var $ = unsafeWindow.jQuery;
$("body").prepend('<button id="tsDownload">DownloadExcel</button>');
$("#tsDownload").click(function(){
   alert("TEST!");
});

The script could add the button, but could not attach the click event, that part is simply ignored. Can you tell me why? Is something related to security? For example after a few I discovered that I had to add the first line to get jQuery from "unsafeWindow".

If I try this code from the console, it works! This is why I guess a security limit of Greasemonkey.

isherwood
  • 58,414
  • 16
  • 114
  • 157
Tobia
  • 9,165
  • 28
  • 114
  • 219

1 Answers1

1

This is a security issue from trying to access the jQuery instance used on the page, which is treated as a separate window and has some restrictions.

This isn't really meant to be done at all, however. Instead you should include your own instance of jQuery in your GreaseMonkey script. You can do that by adding

// @require  https://code.jquery.com/jquery-3.3.1.min.js

To the annotations at the top of your script. Yes, this will mean the script is loaded twice, but it's cached locally and won't mean much.

Amunium
  • 130
  • 1
  • 6
  • If the button is being added doesn't that imply that jQuery is loading properly? – isherwood Mar 22 '19 at 15:23
  • It *is* loading properly, it just has security restrictions when accessing the script outside GM from inside GM. Apparently you can add elements but not assign handlers. Not entirely sure why, but I tested it and it is the case. – Amunium Mar 22 '19 at 15:25
  • It's not enough to just `@require` if the site already has jQuery. You must also set `@grant` other than `none`. See the first duplicate Q&A. – Brock Adams Mar 22 '19 at 15:31
  • Brock Adams - I justed tested it without issues. I found a website that had jQuery included already (console returned jQuery object when I typed `$`), then added a GreaseMonkey script for that and used OP's code, which didn't work; then tried removing the unsafeWindow-line and adding jQuery require instead. Worked just fine. Can't say there aren't features outside of OP's code that would screw up, however. – Amunium Mar 22 '19 at 15:34
  • 1
    @Amunium, that's not how science/engineering/testing works. "I just drove 90 MPH through a school zone just after drinking a case of Schlitz. I didn't hit anybody (important) so it must be okay." – Brock Adams Mar 22 '19 at 16:16
  • 1
    @BrockAdams, Well, that was both unnecessarily condescending and completely wrong. That's exactly how you test things. And your "analogy" makes absolutely no sense. – Amunium Mar 22 '19 at 23:08