每秒扫描页面以查找关键字是否有效?



所以我正在为自己和几个朋友开发一个个人用户脚本。用户脚本用于阻止页面上的关键字。

要在我使用的页面上搜索关键字:

var filter = ["worda", "wordb", "wordc"];
var found = false;
var check =
function () {
//Stores the content of the head and body in the document.
var head = $("head").html();
var body = $("body").html();

$.each(filter, function(index, item) {
if ((head + body).toString().toLowerCase().contains(item.toLowerCase()))  {
window.clearInterval(interval);
console.log("Found: " + item);
found = true;
return false;
}
});
if (found) {
$("body").hide();
var originalTitle = $(document).prop("title");
$(document).prop("title", "Blocked");
window.setTimeout(function() {
if (confirm("This page contains a blocked keyword, are you sure you'd like to continue?")) {
$(document).prop("title", originalTitle);
$("body").show();
return;
}
}, 1);
}
};

然后我将其设置为每秒重复一次:

var interval = window.setInterval(check, 1000);

我每秒重新检查页面的原因是,新内容可能是通过Javascript动态创建的,我需要确保它也被过滤。

但是,我想知道这是否是扫描页面关键字的最有效方法,或者是否有更有效的方法不需要我重新检查整个页面(可能只需要重新检查新元素(。

我也想把间隔推得尽可能低(我想在 100 毫秒左右(,但我不知道这是否会非常资源友好。

谢谢你的帮助。

您说得对,定期扫描页面内容是解决问题的低效方法。话虽如此,如果它每秒只运行一次,那可能没什么大不了的。

不过,还有一个更好的选择。MutationObserver 接口可用于在修改文档或文档的一部分时触发事件。这非常适合您要执行的操作:

var observer = new MutationObserver(function() {
… scan the document for your keywords …
});
observer.observe(document, {
childList: true,
characterData: true,
subtree: true
});

相关内容

最新更新