I want to write a (Scriptish) userscript to include among other things the Freebase suggestion search widget on various web sites. I've tried several approaches to get this to work but no luck so far.
My userscript looks like (take note of the wildcard inclusion):
// ==UserScript==
// @id meta@parsed.nl
// @name Meta
// @version 1.0
// @namespace
// @author
// @description
// @include *
// @run-at document-end
// @require https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.js
// @require http://freebaselibs.com/static/suggest/1.3/suggest.min.js
// @noframes
// ==/UserScript==
$("head").append('<link type="text/css" rel="stylesheet" href="http://freebaselibs.com/static/suggest/1.3/suggest.min.css" />');
$("body").prepend('<input id="freebase-suggest" type="text"/>');
$("#freebase-suggest")
.suggest()
.bind("fb-select", function(e, data) {
alert("");
});
Everything loads fine but when I try to use the search box it doesn't work and the following error is displayed in the error console:
Error: jQuery16101843227533633628_1325186688691 is not defined Source File: http://www.freebase.com/private/suggest?callback=jQuery16101843227533633628_1325186688691&prefix=ron+paul&type_strict=any&all_types=false Line: 1
Apparently the script is using JSONP for cross domain requests and my gut feeling is telling me the callback jQuery16101843227533633628_1325186688691
is being defined in a different context from the document the widget is in (the Scriptish context versus unsafeWindow).
What should I do?
Adding both jQuery and the Freebase suggest script in the DOM and waiting for them to load is enough to make this work. But you do have to reference unsafeWindow
.
var head = document.getElementsByTagName('head')[0];
// Only add jQuery if the site doesn't have it already (to prevent conflicts)
if (typeof unsafeWindow.jQuery === "undefined") {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js';
head.appendChild(script);
}
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'http://freebaselibs.com/static/suggest/1.3/suggest.min.js';
head.appendChild(script);
window.setTimeout(function() {
$ = unsafeWindow.jQuery;
$("head").append('<link type="text/css" rel="stylesheet" href="http://freebaselibs.com/static/suggest/1.3/suggest.min.css" />');
$("body").prepend('<input id="freebase-suggest" type="text"/>');
$("#freebase-suggest")
.suggest()
.bind("fb-select", function(e, data) {
alert("");
});
}, 1000);
I don't know if this approach is smart, but it does work.