如何编写Greasemonkey脚本实现同域iFrame指定div内容匹配时触发
解决方案
你原有代码仅查询了顶层页面的DOM,而同域iframe拥有独立的DOM树,需要通过iframe的contentDocument属性访问内部节点,修改后的可用脚本如下:
// ==UserScript== // @name Script // @include https://www.somesite.com/* // @require http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js // @grant GM_addStyle // ==/UserScript== /*- The @grant directive is needed to work around a design change introduced in GM 1.0. It restores the sandbox. */ var intv = setInterval(function() { // 先获取iframe元素,多iframe场景可替换为更精准的选择器 const iframe = document.querySelector('iframe'); // 兼容判断:确保iframe存在且可访问内部DOM if (!iframe || !iframe.contentDocument) return; // 在iframe内部DOM中查询目标节点 const sp = iframe.contentDocument.querySelector('#10'); // 若只需匹配部分文本,可将判断条件替换为 sp.textContent.includes('指定部分文本') if (sp && sp.textContent.trim() === 'You become 1 best coder') { // 匹配成功后清除定时器,避免重复执行 clearInterval(intv); // 此处添加你的后续业务逻辑 alert('Hello world!'); } }, 5000);
补充说明
- 如果页面存在多个iframe,可使用特征选择器定位目标iframe,比如按src特征匹配:
document.querySelector('iframe[src*="something.php"]') - 新增的
trim()方法可消除文本前后的空白、换行符,避免额外字符导致匹配失败
内容的提问来源于stack exchange,提问作者Scorpys
相关产品推荐
相关产品推荐

