Я пытаюсь создать скрипт greasemonkey (для Opera), чтобы добавить автозаполнение к элементам ввода, найденным на веб-странице, но он не полностью работает.
Сначала я получил работающий плагин автозаполнения:
// ==UserScript==
// @name autocomplete
// @description autocomplete
// @include *
// ==/UserScript==
// Add jQuery
var GM_JQ = document.createElement('script');
GM_JQ.src = 'http://jquery.com/src/jquery-latest.js';
GM_JQ.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(GM_JQ);
var GM_CSS = document.createElement('link');
GM_CSS.rel = 'stylesheet';
GM_CSS.href = 'http://dev.jquery.com/view/trunk/plugins/autocomplete/jquery.autocomplete.css';
document.getElementsByTagName('head')[0].appendChild(GM_CSS);
var GM_JQ_autocomplete = document.createElement('script');
GM_JQ_autocomplete.type = 'text/javascript';
GM_JQ_autocomplete.src = 'http://dev.jquery.com/view/trunk/plugins/autocomplete/jquery.autocomplete.js';
document.getElementsByTagName('head')[0].appendChild(GM_JQ_autocomplete);
// Check if jQuery's loaded
function GM_wait()
{
if(typeof window.jQuery == 'undefined')
{
window.setTimeout(GM_wait,100);
}
else
{
$ = window.jQuery;
letsJQuery();
}
}
GM_wait();
function letsJQuery()
{
$("input[type='text']").each(function(index)
{
$(this).val("test autocomplete");
});
$("input[type='text']").autocomplete("http://mysite/jquery_autocomplete.php", {
dataType: 'jsonp',
parse: function(data) {
var rows = new Array();
for(var i=0; i<data.length; i++){
rows[i] = {
data:data[i],
value:data[i],
result:data[i] };
}
return rows;
},
formatItem: function(row, position, length) {
return row;
},
});
}
Я вижу «тестовое автозаполнение», но с помощью отладчика Opera (firefly) я не вижу сообщений на моей странице php. (да, MySite вымышлен, но он работает здесь)
Пробую на своей странице:
<body>
no autocomplete: <input type="text" name="q1" id="script_1"><br>
autocomplete on: <input type="text" name="q2" id="script_2" autocomplete="on"><br>
autocomplete off: <input type="text" name="q3" id="script_3" autocomplete="off"><br>
autocomplete off: <input type="text" name="q4" id="script_4" autocomplete="off"><br>
</body>
Это работает, но при попытке на других страницах это иногда не будет:
например http://spitsnieuws.nl/ и http://dumpert.nl работают, но http://nu.nl и http://armorgames.com не работают. РЕДАКТИРОВАТЬ: оба дают
Неопределенное исключение: Ошибка типа:
'$ ( "Вход [тип = 'Текст']"). Автополный'
не является функцией
Попытка автозаполнения JQuery UI имеет больше проблем:
// ==UserScript==
// @name autocomplete
// @description autocomplete
// @include *
// ==/UserScript==
// Add jQuery
var GM_JQ = document.createElement('script');
GM_JQ.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js';
GM_JQ.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(GM_JQ);
var GM_CSS = document.createElement('link');
GM_CSS.rel = 'stylesheet';
GM_CSS.href = 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css';
document.getElementsByTagName('head')[0].appendChild(GM_CSS);
var GM_JQ_autocomplete = document.createElement('script');
GM_JQ_autocomplete.type = 'text/javascript';
GM_JQ_autocomplete.src = 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js';
document.getElementsByTagName('head')[0].appendChild(GM_JQ_autocomplete);
// Check if jQuery's loaded
function GM_wait()
{
if(typeof window.jQuery == 'undefined')
{
window.setTimeout(GM_wait,100);
}
else
{
$ = window.jQuery;
letsJQuery();
}
}
GM_wait();
// All your GM code must be inside this function
function letsJQuery()
{
$("input[type='text']").each(function(index)
{
$(this).val("test autocomplete");
});
$("input[type='text']").autocomplete({
source: function(request, response) {
$.ajax({
url: "http://mysite/jquery_autocomplete.php",
dataType: "jsonp",
success: function(data) {
response($.map(data, function(item) {
return {
label: item,
value: item
}
}))
}
})
}
});
}
Это будет работать на моей html-странице, http://spitsnieuws.nl и http://dumpert.nl, но не на http://nu.nl и http://armorgames.com (то есть в качестве плагина)
Однако ошибка в nu и armorgames теперь:
http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css
Declaration syntax error
Line 18:
100%; top: 0; left: 0; position: absolute; opacity: 0; filter:Alpha(Opacity=0);
--------------------------------------------------------------------------------^
Элементы ввода:
//http://spitsnieuws.nl
<input class="frmtxt ac_input" type="text" id="zktxt" name="query" autocomplete="off">
//http://dumpert.nl
<input type="text" name="srchtxt" id="srchtxt">
//http://nu.nl
<input id="zoekfield" name="q" type="text" value="Zoek nieuws" onfocus="this.select()" type="text">
//http://armorgames.com
<input type="text" name="search" value="" class="search">
Кто-нибудь знает, почему функция автозаполнения не работает? Почему не делается запрос на страницу php? И почему я не могу добавить автозаполнение на google.com?
Edit:
Добавлены armorgames и сообщения об ошибках
Ответ
Ну, я обнаружил, что мне также следует проверить, загрузился ли autocomplete.js (а не только jquery.js)
С автозаполнением jQuery UI
// ==UserScript==
// @name autocomplete
// @description autocomplete
// @include *
// ==/UserScript==
// Add jQuery
var GM_CSS = document.createElement('link');
GM_CSS.type = 'text/css';
GM_CSS.rel = 'stylesheet';
GM_CSS.href = 'http://mysite/jquery/development-bundle/themes/ui-lightness/jquery.ui.all.css';
document.getElementsByTagName('head')[0].appendChild(GM_CSS);
function includeJS(jsPath)
{
var script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.setAttribute("src", jsPath);
document.getElementsByTagName("head")[0].appendChild(script);
};
includeJS("http://mysite/jquery/development-bundle/jquery-1.4.2.js");
includeJS("http://mysite/jquery/development-bundle/ui/jquery.ui.core.js");
includeJS("http://mysite/jquery/development-bundle/ui/jquery.ui.widget.js");
includeJS("http://mysite/jquery/development-bundle/ui/jquery.ui.position.js");
// Check if jQuery's loaded
function GM_wait()
{
if(typeof window.jQuery == 'undefined')
{
window.setTimeout(GM_wait,100);
}
else
{
$ = window.jQuery;
letsJQuery();
}
}
GM_wait();
// All your GM code must be inside this function
function letsJQuery()
{
$("input[type='text']").each(function(index)
{
$(this).val("test autocomplete");
});
//wait till script is loaded
$.getScript("http://mysite/jquery/development-bundle/ui/jquery.ui.autocomplete.js", function(){
//using remote data from other domain using JSONP
$("input[type='text']").autocomplete({
source: function(request, response) {
$.ajax({
url: "http://mysite/jquery_autocomplete.php",
dataType: "jsonp",
success: function(data) {
response($.map(data, function(item) {
return {
label: item,
value: item
}
}))
}
})
}
});
});
}