#greasemonkey-4
#greasemonkey-4
Вопрос:
Я пытаюсь сохранить некоторые значения, которые будут сохраняться при загрузке страницы и закрытии браузера в Greasemonkey. Мой код выглядит следующим образом:
// @name Netflix saw it button
// @description Apparently Netflix can't afford enough storage space or programmers to make it easy to know which shows you've seen before. This fixes that. Unfortunately, it will only store data in one browser at a time so you have to use the same computer and browser for the data to store. Sorry about that, but I'm not a Netflix tech so this is the best we got.
// @version 1
// @include https://www.netflix.com/*
// @grant none
// @grant GM.getValue
// @grant GM.setValue
// @require https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js
// ==/UserScript==
$(document).ready(function() {
$('[data-tracking-uuid]').each(function(){
id= $(this).data('tracking-uuid');
console.log(id);
console.log(typeof id);
GM.setValue(id,1);
console.log(GM.getValue(id));
if(GM.getValue($(this).data('tracking-uuid')))
$(this).closest('.title-card-container').addClass('g_watched');
});
});
Как вы можете видеть, я тестирую постоянное хранилище, но это не дает мне ожидаемых результатов. Когда я проверяю консоль, я вижу идентификатор, а тип идентификатора — string (который требуется для GM.setValue). В самой следующей строке, когда он пытается установить значение, он прекращает выполнение JS, и никакие другие строки не выполняются. Ошибка не выдается. Он просто умирает.
Это было то же самое, когда у меня там не было setvalue, а было только getvalue (которое должно возвращать значение null, если оно не было установлено ранее). Что я делаю не так? Это Greasemonkey> 4.0, так что это должен быть правильный синтаксис, но без каких-либо ошибок или отзывов я застрял.
Ответ №1:
GM.getValue
amp; GM.setValue
являются async
, что означает, что вы должны дождаться его, прежде чем двигаться дальше.
Пример, объясняющий процесс:
// set value
GM.setValue(id,1); // async operation
// script runs but value is still in the process of setting
const a = GM.getValue(id); // async operation
// script runs but value is still in the process of getting
console.log(a); // a is not set yet
Как исправить вышеупомянутую проблему с асинхронностью
(async() => {
// set value
await GM.setValue(id,1); // async opertaion wait for it before moving on
const a = await GM.getValue(id); // async opertaion wait for it before moving on
console.log(a); // a is avialble
})();
Вот пример вашего скрипта с async/await
Во-первых, @grant none
конфликты с @grant GM.getValue
и т. Д
// @name Netflix saw it button
// @description Apparently Netflix can't afford enough storage space or programmers to make it easy to know which shows you've seen before. This fixes that. Unfortunately, it will only store data in one browser at a time so you have to use the same computer and browser for the data to store. Sorry about that, but I'm not a Netflix tech so this is the best we got.
// @version 1
// @include https://www.netflix.com/*
// @grant GM.getValue
// @grant GM.setValue
// @require https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js
// ==/UserScript==
$(document).ready(async function() {
$('[data-tracking-uuid]').each(function(){
id= $(this).data('tracking-uuid');
console.log(id);
console.log(typeof id);
await GM.setValue(id,1);
console.log(await GM.getValue(id));
if(await GM.getValue($(this).data('tracking-uuid')))
$(this).closest('.title-card-container').addClass('g_watched');
});
});
Ответ №2:
Я опубликовал это на Github и получил ответ. Значение grant none аннулирует все остальные, поэтому его необходимо удалить.
Кроме того, методы set и get value в 4.0 являются «обещаниями», поэтому вам нужно использовать их как таковые (что в моем случае означало использование await для обеспечения синхронности).
Комментарии:
1. Часы поиска в Google, и это была одна строка
// @grant none
аааа