无法为特定页面挂载Tampermonkey脚本,点击按钮触发报错
问题:Tampermonkey脚本导致页面按钮点击报错
我正在编写一个简单的Tampermonkey脚本,给某需账号访问的页面卡片添加提示框,但即便简单的提示框代码,也导致页面报错、无法正常使用。
我的脚本代码
(function() { 'use strict'; var $ = window.jQuery; $( document ).ready(function() { if $( ".cardtitle" ) !== 'undefined' ) { $( ".cardtitle" ).prop('title', 'What an awesome tooltip'); } }); })();
报错情况
点击“Recuperar Lista”按钮时,页面出现以下错误:
Uncaught TypeError: Cannot read properties of undefined (reading 'close')
at HTMLInputElement.onclick (?view=cards/lista:32:103)
对应页面的代码行:
<div align="center" class="popup-cards-from-storage-btns"> <input type="button" class="botao botao-mob-100" value="Recuperar Lista" onclick="wizard.updateJsonByLembrarDecisaoOpcional(); wizard.show(); $.modal.close(); analytics.gaTrack('ListaCards - Aceitou lista de cards');" /> ^^=== 这就是报错信息里提到的第32行 ======= <input type="button" class="botao botao-mob-100 botao-preto" value="Ignorar Lista" onclick="wizard.clearLembrarDecisaoOpcional(); wizard.show(); $.modal.close(); analytics.gaTrack('ListaCards - Recusou lista de cards');" /> </div>
我知道页面是动态生成的,元素可能在ready事件触发时还未加载,但不解为何脚本注入会引发该报错。
解决方案
1. 修复脚本语法错误
你的脚本存在明显语法错误:if $( ".cardtitle" ) !== 'undefined' ) 缺少左括号,且jQuery选择器永远返回jQuery对象,不会等于undefined,判断元素是否存在应使用.length属性。
修正后的脚本:
(function() { 'use strict'; var $ = window.jQuery; $( document ).ready(function() { // 通过length判断元素是否存在 if ( $( ".cardtitle" ).length > 0 ) { $( ".cardtitle" ).prop('title', 'What an awesome tooltip'); } }); })();
2. 适配动态生成元素(可选)
由于页面元素是动态生成的,ready事件触发时.cardtitle可能尚未渲染,推荐使用以下两种方式处理:
方式一:用MutationObserver监听元素加载
(function() { 'use strict'; var $ = window.jQuery; const observer = new MutationObserver((mutations) => { mutations.forEach(mutation => { if (mutation.addedNodes.length) { // 处理新增节点中的.cardtitle元素 $(mutation.addedNodes).find('.cardtitle').addBack('.cardtitle').prop('title', 'What an awesome tooltip'); } }); }); observer.observe(document.body, { childList: true, subtree: true }); })();
方式二:利用jQuery事件委托
如果.cardtitle的父容器固定存在,可通过事件委托实现:
(function() { 'use strict'; var $ = window.jQuery; $(document).on('mouseenter', '.cardtitle', function() { // 鼠标hover时设置title,避免重复操作 if (!$(this).prop('title')) { $(this).prop('title', 'What an awesome tooltip'); } }); })();
3. 脚本触发按钮报错的原因
原脚本的语法错误会导致Tampermonkey注入时干扰页面原有jQuery环境——比如异常抛出破坏全局作用域变量(如$.modal),或脚本执行异常影响页面原生JS逻辑。修复语法错误后,该问题大概率会消失。
内容的提问来源于stack exchange,提问作者douglaslps
相关产品推荐
相关产品推荐

