5
I started programming Userscripts in Chrome and almost all snippets of code I find work, but when going pro Firefox gives problem. In Chrome I use the Tampermonkey and in Firefox the Scriptish (which is a Fork greasemonkey).
[Note to future visitors, advise against emphatically working with Scriptish, there are things that run smoothly in GM and TM but not in it.]
For example, if I add a script in the DOM, whose return is a JSONP, the function callback
(global) of JSONP gives undefined
in FF. Or, if I make an AJAX call, at the time of executing a global function within the success
also gives undefined
in FF.
I made a reduced version that demonstrates the problem. The function global_function
runs on Chrome but not on FF. The execution domain is SOPT and the AJAX call is to the Stack Exchange API.
// ==UserScript==
// @name (SOPT) FF problems
// @namespace sopt.se
// @author brasofilo
// @include /*
// @description Testando problemas no FF
// ==/UserScript==
jquery_url = '//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js'
global_function = function() {
alert( 'yes!' );
}
/**
* Chamada depois que o jQuery foi carregado
*/
function jqueryLoaded() {
jQ.ajax({
url: 'http://api.stackexchange.com/2.2/users',
data: { order: 'desc', sort: 'reputation', site: 'stackoverflow' },
type: 'get',
dataType: 'json',
cache: false,
success: function(data) {
console.log(data);
global_function();
}
});
}
/**
* Carrega jQuery e chama callback quando carregar
* Nota: jQ substitui $ para evitar conflitos
*
* https://stackoverflow.com/a/3550261/1287812
*/
function addJQuery( callback ) {
var script = document.createElement( 'script' );
script.setAttribute( 'src', jquery_url );
script.addEventListener( 'load', function() {
var script = document.createElement('script');
script.textContent = 'window.jQ=jQuery.noConflict(true);(' + callback.toString() + ')();';
document.body.appendChild( script );
}, false );
document.body.appendChild( script );
}
addJQuery( jqueryLoaded );
I tried to window.global_function = function(){ }
, function global_function() {}
, unsafeWindow.global_function = function(){ }
and following undefined
. And I checked the following discussions but I didn’t clarify anything...
- Greasemonkey Script and Function Scope
- Greasemonkey & global variables
- Greasemonkey Script and Function Scope
How to resolve this issue of Scope? And in addition, there are other basic differences when programming Userscripts for Chrome and Firefox?
Stackoverflow already carries the jQuery. The code you run within script tags could access the stackoverflow jquery without having to load the library again.
– hugomg