Я написал UserScript для Greasemonkey (Firefox) и тестирую его на совместимость с Chrome Tampermonkey и получаю ошибки в консоли разработчика:
Uncaught TypeError: Cannot read property 'profile_url' of undefined
Uncaught TypeError: Cannot read property 'encoded_name' of undefined
Ошибки, кажется, ссылаются на обратный вызов onreadystatechanged
для GM_xmlhttpRequest
, который вызывается следующим образом:
var flairs = document.querySelectorAll('span.flair');
var steam_re = /(?:(?:https?:\/\/)?www\.)?(?:steam|pc)(?:community\.com\/?(?:(id|profiles)\/?)?|[\s\-_]*id)?[\/:\s\|]*(.{2,}?)(?:[\/|:\-\[(] ?(?:\/?(?:ghost|enforcer|tech|mm|master))+[\[)]?)?$/i
function get_text(e) { return e.innerText || e.textContent; }
function set_text(e, t) {
if (e.innerText)
e.innerText = t;
else
e.textContent = t;
}
var parser = new DOMParser();
for (var i = 0; i < flairs.length; i++) {
var text = get_text(flairs[i]);
var match = steam_re.exec(text);
if (match == null || match.length < 3)
continue;
var type = match[1] || 'id';
var name = encodeURIComponent(match[2]);
var url = 'http://steamcommunity.com/' + type + '/' + name;
var xml_url = url + '?xml=1';
GM_xmlhttpRequest({
method: 'GET',
url: xml_url, // Link to a steam profile with ?xml=1 added
accept: 'text/xml',
context: {
flair_index: i,
flair_text: text, // textContent of span element
encoded_name: name,
profile_url: url, // Link to steam profile
query_url: xml_url
},
onreadystatechange: function(response) {
if (response.readyState != 4)
return;
// Attempt to fall back to alternate forms of context,
// none of which works. response.context works on Firefox/Greasemonkey.
var context = response.context || this.context || context;
var doc = parser.parseFromString(response.responseText, 'text/xml');
var validProfile = doc.documentElement.nodeName == 'profile';
var a = document.createElement('a');
a.href = validProfile ?
context.profile_url : // TypeError here, context is undefined
('http://steamcommunity.com/actions/SearchFriends?K=' + context.encoded_name);
a.className += (validProfile ? 'steam-profile-link' : 'steam-profile-search-link');
var a_text = document.createTextNode(context.flair_text);
a.appendChild(a_text);
set_text(flairs[context.flair_index], '');
flairs[context.flair_index].appendChild(a);
}
});
}
Сама функция вызывается нормально, и вызывается обратный вызов, но как только я пытаюсь получить доступ к переменной context
внутри нее, она не определена.
Все это работает, как и ожидалось, в Firefox. Что он делает, так это перебирает span
элементов, которые имеют класс «flair», и проверяет с помощью регулярного выражения, содержат ли они имя пользователя Steam, и если да, то делает его ссылкой на их страницу SteamCommunity. (Полный исходный код на github). Скрипт работает на /r/PaydayTheHeistOnline.
Я протестировал использование массива, определенного вне функции, для хранения данных вместо использования свойства контекста, переданного в xmlhttpRequest, но я получаю точно такую же ошибку.