javascript - 基本的greasemonkey脚本遇到问题 - GM.getValue / GM.setValue(我认为)
问题描述
我正在尝试编写一个基本的 Greasemonkey 脚本,但遇到了一些问题。本质上,该脚本将刷新页面并计算页面上的图像数量。如果图像数量增加,它会提醒我并使该选项卡处于活动状态。如果图像数量相同或更少,它将以设定的时间间隔继续刷新页面。
我认为,根据我所看到的,最好的做法是使用 GM.getValue / GM.setValue 来存储图像数量以将其与新图像计数进行比较。虽然我似乎无法让它运行 - 我认为我的逻辑是合理的,但这只是一个语法问题,尽管尝试了不同的变体。我以前从未使用过Javascript!
// ==UserScript==
// @name *Page Refresher
// @include *
// ==/UserScript==
// @grant GM.getValue
// @grant GM.setValue
var refreshRate = 10000; //Refreshes every 10s
var newCount =document.images.length; //Counts images on page
if (GM.getValue('oldCount',-1) === -1){
GM.setValue('oldCount',newCount);
window.setTimeout(function(){window.location.reload() ;},refreshRate);
} else {
if (newCount <= GM.getValue('oldCount')){
GM.setValue('oldCount',newCount);
window.setTimeout(function(){window.location.reload() ;},refreshRate);
} else {
if (newCount > GM.getValue('oldCount')){
GM.setValue('oldCount',newCount);
alert('More images!');
}
}
这是我正在使用的粗略代码。我只是不确定我哪里出错了——我敢肯定这是很简单的事情,但我肯定在挣扎。谢谢!
解决方案
GM4 中的那些函数(如GM.getValue)是异步的。这意味着它们返回的值不会像同步 API 那样立即可用。
在异步代码中,您需要等待响应。
注意:您应该一次获取 oldCount 的值并将其缓存,而不是从存储值中一遍又一遍地获取。元数据块也有错误。
这是基于您的代码的示例(代码简化)
// ==UserScript==
// @name Page Refresher
// @include *
// @grant GM.getValue
// @grant GM.setValue
// ==/UserScript==
(async () => {
const refreshRate = 10000; // Refreshes every 10s
const newCount = document.images.length; // Counts images on page
const oldCount = await GM.getValue('oldCount', -1);
await GM.setValue('oldCount', newCount); // save new value, wait since refreshing before saving can cause issues
if (newCount > oldCount){
alert('More images!');
}
else {
setTimeout(() => { location.reload(); }, refreshRate);
}
})();
推荐阅读
- ios - 连接到蜂窝数据提供商时 iOS 请求超时错误
- event-handling - 使用 PreHandler AX7 从 SalesEditLines 表单 formRun 获取 SalesFormLetter 类
- android - 如何使用 dagger 2.11 注入 ViewModel
- jquery - 无法识别的表达式::nth-child
- matrix - 为问答实施注意力池网络的问题
- javascript - Web Speech API 用单个字母“组成”整个单词(德语中的“p”->“police”)
- azure - Powershell / Azure Functions - 使用 appid 和 appsecret 连接时出现问题 - 访问被拒绝
- c# - 使用 linq 分组和排序
- java - 如何知道 List 对象是否具有固定大小
- c# - 如何使用 Raycast 在 ARkit 中旋转模型并统一触摸?