Skip to content

Instantly share code, notes, and snippets.

@Bluefissure
Last active February 10, 2025 05:54
Show Gist options
  • Save Bluefissure/88e2233e904f3ff3d0d515a59f03b43b to your computer and use it in GitHub Desktop.
Save Bluefissure/88e2233e904f3ff3d0d515a59f03b43b to your computer and use it in GitHub Desktop.
XPath Change Notifier
// ==UserScript==
// @name XPath Change Notifier
// @namespace http://tampermonkey.net/
// @version 1.4
// @description 每分钟检测指定 XPath 元素是否发生变化
// @author Bluefissure
// @match https://us-store.msi.com/*
// @match https://www.bestbuy.com/site/*
// @grant GM_notification
// @grant GM_setValue
// @grant GM_getValue
// @grant GM_deleteValue
// @grant GM_listValues
// @grant GM_registerMenuCommand
// ==/UserScript==
(function() {
'use strict';
const XPATHS = {
"us-store.msi.com": '//div[@class="row"]/div/button[contains(@class, "btn add-cart-button")]',
"www.bestbuy.com": '//div[contains(@class, "row m")]//button[contains(@class, "add-to-cart-button")]'
};
let changeDetected = false;
function getXPathElement(xpath) {
let result = document.evaluate(xpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
return result.singleNodeValue ? result.singleNodeValue.innerText.trim() : null;
}
function checkForChanges() {
let host = window.location.hostname;
let path = window.location.pathname;
if (!XPATHS[host]) return;
let pageKey = `lastValue_${host}_${path}`;
let currentValue = getXPathElement(XPATHS[host]);
let previousValue = GM_getValue(pageKey, "");
console.log(`目标元素:${XPATHS[host]}`);
console.log(`currentValue:${currentValue}`);
console.log(`previousValue:${previousValue}`);
console.log(`changeDetected:${changeDetected}`);
if (currentValue === null) {
notifyChange("目标元素未找到", host);
return;
}
if (currentValue !== previousValue) {
if (previousValue.trim() === '') {
location.reload();
}
GM_setValue(pageKey, currentValue);
notifyChange(currentValue, host);
changeDetected = true;
} else {
console.log("Sleeping 60 seconds...");
}
}
function notifyChange(newValue, host) {
GM_notification({
title: `页面更新通知 (${host})`,
text: `检测到目标元素变化: ${newValue}`,
timeout: 5000,
onclick: function() { window.focus(); }
});
}
function waitForPageLoad(callback) {
if (document.readyState === "complete") {
callback();
} else {
window.addEventListener("load", callback);
}
}
function clearStoredValues() {
let keys = GM_listValues();
keys.forEach(key => GM_deleteValue(key));
alert("所有存储的数据已清除!");
}
GM_registerMenuCommand("清除存储数据", clearStoredValues);
waitForPageLoad(() => {
setInterval(() => {
if (!changeDetected) {
location.reload();
}
}, 60 * 1000);
checkForChanges();
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment