I have a basic greasemonkey script shown below, in which I want to run some code every time an AJAX request is sent by the website I’m running the script on.
I’m using the ajaxSuccess jQuery handler and it’s not being fired. I suspect this might be because the AJAX requests are being sent with the global flag set to false (see http://docs.jquery.com/Ajax_Events). Is there some better way to achieve this that will work even when global is set to false?
Code:
// ==UserScript==
// @name MyTestScript
// @require http://code.jquery.com/jquery-1.7.1.min.js
// @namespace NRA
// @include http://www.mysamplewebsite.com/view/*
// ==/UserScript==
$(document).ajaxSuccess(function(e, xhr) {
alert("ajax success hit!");
// I will do my other handling here
});
Thanks
The jQuery in your userscript runs in a separate environment from the page’s jQuery.
You need to intercept the page’s AJAX calls so you can use either (A)
unsafeWindowor (B) Inject your script.(A)
unsafeWindowlooks like:(B) Script injection looks like:
Note that in both cases, you must be conscious that data does not flow from page scope back to GM scope easily — be careful about mixing the two.
One workaround, for transmitting data across the sandbox, can be found in this answer.