// ==UserScript==
// @name test
// @namespace http://tampermonkey.net/
// @version 0.1
// @description try to take over the world!
// @author You
// @match https://live.bilibili.com/*
// @grant none
// ==/UserScript==
(function() {
'use strict';
;(function func() {
const injectAnchor = document.getElementsByClassName('right-action')[0]
console.log(injectAnchor)
if (injectAnchor) {
console.log('find injectAnchor')
} else {
requestAnimationFrame((function () {
func()
}))
}
})();
})();
就是用requestAnimationFrame
找包含right-action
这个类的元素,找到就停止。
这段代码直接放控制台执行就没问题(chrome浏览器)。
但是放到tampermonkey里就会无限执行,找到了类也停不下来。
求解这是为什么?
参考GPT和自己的思路:
可能是因为Tampermonkey脚本与页面中正在加载的其他脚本和元素的交互方式不同,导致requestAnimationFrame
函数无法正确地停止循环。你可以尝试使用clearAnimation
或cancelAnimationFrame
函数来手动停止动画循环,或者使用其他的元素查找方法来寻找right-action
元素,例如使用jQuery的选择器。另外,建议在调试脚本时关闭浏览器的缓存,以便更好地观察脚本的行为。