I started programming UserScripts in Chrome and almost all of the code snippets I find work, but when it comes to Firefox it's a problem. In Chrome I use Tampermonkey and in Firefox Scriptish (which is a fork of Greasemonkey).
[Note to future visitors, I strongly advise against working with Scriptish, there are things that run smoothly on GM and TM but not on it.]
For example, if I add a script in the DOM whose return is a JSONP, the callback
(global) function of JSONP gives undefined
to the FF. Or, if I make an AJAX call, at the time of executing a global function within success
it also gives undefined
in FF.
I did a reduced version that demonstrates the problem. The global_function
function runs in Chrome but not in 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 http://pt.stackoverflow.com/*
// @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've tried window.global_function = function(){ }
, function global_function() {}
, unsafeWindow.global_function = function(){ }
and follow undefined
. And I checked the following discussions but did not clarify anything ...
- Greasemonkey Script and Function Scope
- Greasemonkey & global variables
- Greasemonkey Script and Function Scope
How to resolve this scope issue? And besides, are there other basic differences when programming UserScripts for Chrome and Firefox?